Consider the class
template <typename T>
struct Foo {
Foo(const Foo<T>& other) {}
};
For the constructor argument type, is const Foo<T>&
and const Foo&
the same in this context? I always assumed not, thinking that the latter can be called for Foo<int> f = Foo<float>()
, and the former cannot. But now I'm not sure if that is so.
Within a class template, class template parameters have one unique meaning for every instantiation. That means that Foo<int>
has T==int
, and thus the templated ctor is Foo<int>::Foo(const Foo<int>& other)
.
It is possible to have additional template parameters, though :
template <typename T>
struct Foo {
template <typename U>
Foo(const Foo<U>& other) {}
};
Now T
can be different from U
.
Yes, it's the same.
This is due to the injected-class-name. The class name is inserted into the scope of all classes so that name lookup acts sensibly. When the injected-class-name is used as a type name in a template class, it's equivalent to the template name followed by the template parameters enclosed in <>
([temp.local]/1
), so Foo
is equivalent to Foo<T>
in that context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With