Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For an argument of the template class Foo method, is "Foo&" and "Foo<T>&" the same?

Tags:

c++

templates

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.

like image 751
Violet Giraffe Avatar asked Dec 08 '22 21:12

Violet Giraffe


2 Answers

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.

like image 116
MSalters Avatar answered Apr 14 '23 06:04

MSalters


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.

like image 33
TartanLlama Avatar answered Apr 14 '23 06:04

TartanLlama