Reputation: 39881
As you can see in the code below method get
is templated.
struct A
{
int i;
char c;
};
class SL
{
static void* m_a;
public:
template <class T>
static T* get()
{
return static_cast<T*>(m_a);
}
};
void* SL::m_a = new A{12, 'C'};
int main()
{
std::cout << SL::get<A>()->i;
return 0;
}
What I do not understand is when I write SL::get<B>()
how a compiler creates two methods with the same name, in the same namespace, with two different return types that both does not have parameters, i.e. does not have different argument list? How they overload each-other? Or it is wrong to understand temple function generation to have the same names and interpret their call via overload resolution?
Upvotes: 3
Views: 1154
Reputation: 29976
Templates are prone to name mangling as anything else. When the exact get
is generated, it's not really called get
anymore, it will be called something like get@YUQIE
or similar. You can check this article for an example. This is implementation-defined though, so different compilers will do it in a different way. For example, in the following code
template <class T>
T get()
{
return T();
}
int main()
{
get<int>();
get<char>();
return 0;
}
get
was mangled by gcc as _Z3getIiEPT_v
for get<int>
and _Z3getIcEPT_v
for get<char>
.
Upvotes: 2
Reputation: 36503
This is compiler specific and you shouldn't worry about it too much. A general idea of how it's done though:
Say you call the templated method with 2 different types
SL::get<A>();
SL::get<B>();
The compiler generates 2 new methods for these calls:
static A* get_a()
{
// etc..
}
and
static B* get_b()
{
// etc..
}
This may differ from compiler to compiler but it shows how a compiler avoids name clashes. To the programmer, it's the same method being called twice, to a compiler it's just 2 different methods called by different pieces code.
Upvotes: 3
Reputation: 4660
Template instantions are really different functions which are not overloaded.
You may think of the template parameters <B>
as a part of the function name.
So SL::get<A>
and SL::get<B>
are really different functions (though stemming from the same template).
Quoting from cppreference:
Template argument deduction takes place after the function template name lookup (which may involve argument-dependent lookup) and before overload resolution.
As you see, overload resolution is a different process.
Upvotes: 6