考虑这个类
template <typename T>
struct Foo {
Foo(const Foo<T>& other) {}
};
对于构造函数参数类型,在这个上下文中,const Foo<T>&
和const Foo&
是一样的吗?我一直以为不是,认为后者可以用于Foo<int> f = Foo<float>()
,而前者不能。但现在我不确定是否如此。
在类模板中,每个实例化都有唯一的意义。这意味着Foo<int>
具有T==int
,因此模板构造函数为Foo<int>::Foo(const Foo<int>& other)
。
但是,可以有额外的模板参数:
template <typename T>
struct Foo {
template <typename U>
Foo(const Foo<U>& other) {}
};
T
可以和 U
不同。是的,它们是相同的。
这是由于“injected-class-name”(注入类名)所致。该类名被插入到所有类的范围内,以使名称查找行为明智。当在模板类中使用注入类名作为类型名时,它等效于模板名称后跟用<>
括起来的模板参数([temp.local]/1
),因此在这种情况下,Foo
等价于 Foo<T>
。
class Foo
和class Foo<T>
。 - peterchen