【问题标题】:How to construct objects of nested class templates with the same argument?如何构造具有相同参数的嵌套类模板的对象?
【发布时间】: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&lt;S&lt;S&lt;int&gt;&gt;&gt;{S&lt;int&gt;{0}};...等
  • 或者,提供来自int的转换构造函数。
  • @songyuanyao 这不是很优雅。
  • @chaosink 只允许一次隐式转换,因此不可能将0 转换为S&lt;&gt; 然后再转换为S&lt;S&lt;&gt;&gt; 然后...一次。
  • @chaosink 然后,将您的附加构造函数模板化:godbolt.org/z/W5u7Xt

标签: c++ constructor class-template


【解决方案1】:

您可以添加第二个转换构造函数。如果您想支持任何类型,只需将此构造函数模板化即可:

template <typename T>
struct S {
   T v;

   S(T v) : v{v} {}

   template <typename U>
   S(U v) : v{v} {}
};

这项工作如下:

   S<int>{0};          
   S<S<int>>{0};       
   S<S<S<int>>>{0};    
   S<S<S<S<int>>>>{0}; 

   S<double>{0.0};
   S<S<double>>{0.0};       
   S<S<S<double>>>{0.0};    
   S<S<S<S<double>>>>{0.0}; 

现场演示:https://godbolt.org/z/NKEGRz

请注意,在最底层,两个构造函数都适用,但将根据 C++ 重载规则选择非模板化的构造函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2019-06-04
    • 2010-09-07
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多