关于模板类中的模板函数的小问题

Vol*_*ire 1 c++ templates

我试图理解一些C++语法:

template<class T>
class Foo 
{
   Foo();

   template<class U>
   Foo(const Foo<U>& other);
};

template<class T>
Foo<T>::Foo() { /*normal init*/ }

template<class T>
template<class U>
Foo<T>::Foo(const Foo<U>& other) { /*odd copy constructed Foo*/ }
Run Code Online (Sandbox Code Playgroud)

所以,我编写了这样的代码,它恰好在windows和linux中编译.我不明白的是复制构造函数有两个模板定义的原因.基本上,在我找到正确的语法之前,我必须先解释一下,我想知道为什么特定的语法是正确的,而不是像template<class T, class U>.

Kla*_*aim 7

第一个模板(带参数T)表示该类是用参数T模板化的.

第二个模板(带参数U)表示模板化类的成员函数(带参数T)使用参数U进行模板化 - 即构造函数.

实际上,这里有一个模板类,它将生成与用作构造函数参数的类型一样多的复制构造函数.

在复制构造函数的特定情况下,您不应该这样做,而是:

template<class T>
class Foo 
{
   Foo();

   Foo(const Foo<T>& other);
};

template<class T>
Foo<T>::Foo() { /*normal init*/ }

template<class T>
Foo<T>::Foo(const Foo<T>& other) { /*odd copy constructed Foo*/ }
Run Code Online (Sandbox Code Playgroud)

因为在你的例子中,它不是复制构造函数,而是将类型U作为参数的构造函数:转换构造函数......很难预测.