Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

c++20 - c++ container inside another container

#include <bits/stdc++.h>

template <typename T>
struct Row {
    Row() { puts("Row default"); }
    Row(const Row& other) { puts("Row copy"); }
    Row(Row&& other) { puts("Row move"); }
    Row(T x) { puts("Row int"); }
};

int main() {
  Row<Row<int>> x (10); // this works
  Row<Row<int>> x2 = 10; // error
}

Why the code doesn't work? I know that first one performs direct initialization and the second one is copy initialization but still when it comes to container inside a container I doesn't get easy for me.

compiler: clang c++20

Error message:

no viable conversion from 'int' to 'Row<Row >'

Row<Row> x2 = 10

question from:https://stackoverflow.com/questions/65546400/c-container-inside-another-container

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Problem is that copy initialization is less permissive than direct initialization:

> In addition, the implicit conversion in copy-initialization must produce T
  directly from the initializer, while, e.g. direct-initialization expects
  an implicit conversion from the initializer to an argument of T's constructor.

as initialization from int requires 2 conversions (from int to Row<int> and from Row<int> to Row<Row<int>>), direct initialization allows it but copy initialization does not. You can see it in documentation example as well:

struct S { S(std::string) {} }; // implicitly convertible from std::string
S s("abc"); // OK: conversion from const char[4] to std::string
S s = "abc"; // Error: no conversion from const char[4] to S
S s = "abc"s; // OK: conversion from std::string to S

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...