【发布时间】:2020-05-27 06:21:01
【问题描述】:
如何构造具有相同参数的嵌套类模板的对象?
如何编写构造函数来编译下面的代码?
template<typename T>
struct S {
T v;
S(T v) : v{v} {}
};
int main() {
S<int>{0}; // OK.
S<S<int>>{0}; // OK.
S<S<S<int>>>{0}; // Compilation error. I want this to compile.
S<S<S<S<int>>>>{0}; // Compilation error. I want this to compile.
// ... // I want more...
}
编译错误:
no matching constructor for initialization of 'S<S<S<int> > >'
no matching constructor for initialization of 'S<S<S<S<int> > > >'
【问题讨论】:
-
你必须写成
S<S<S<int>>>{S<int>{0}};...等 -
或者,提供来自
int的转换构造函数。 -
@songyuanyao 这不是很优雅。
-
@chaosink 只允许一次隐式转换,因此不可能将
0转换为S<>然后再转换为S<S<>>然后...一次。 -
@chaosink 然后,将您的附加构造函数模板化:godbolt.org/z/W5u7Xt。
标签: c++ constructor class-template