gpt4 book ai didi

另一个容器内的c++容器

转载 作者:行者123 更新时间:2023-12-03 10:04:57 28 4
gpt4 key购买 nike

#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
}
为什么代码不起作用?我知道第一个执行直接初始化,第二个是复制初始化,但是当涉及到容器内的容器时,我对我来说并不容易。
编译器:clang c++20
错误信息:

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

Row<Row> x2 = 10

最佳答案

问题是copy 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.
作为来自 int 的初始化需要 2 次转换(从 intRow<int> 和从 Row<int>Row<Row<int>>),直接初始化允许,但复制初始化不允许。您也可以在文档示例中看到它:
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

关于另一个容器内的c++容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65546400/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com