Reputation: 5829
Is the following specialization of the member function template bar
valid? It compiles on gcc 4.5.3 and VS .NET 2008. I'm confused because I vaguely recall reading that function templates cannot be specialized.
struct Foo
{
template<typename T>
void bar();
};
template<typename T>
void Foo::bar(){}
template<>
void Foo::bar<bool>(){}
int main()
{
Foo f;
f.bar<char>();
f.bar<bool>();
}
Upvotes: 0
Views: 106
Reputation: 32994
Function template partial specialization was considered in C++11 but was rejected since function template overloading can be used to solve the same issue. However, there're some caveats which have to be looked for when doing this.
Example:
template <typename T> void foo(T);
void foo(int);
foo(10); // calls void bar(int)
foo(10.f); // calls void bar(T) [with T = float]
foo(10u); // calls void bar(T) [with T = unsigned int]!!
For your case, something of this sort might work
struct Foo
{
template<typename T>
void bar(T dummy);
void bar(bool dummy);
};
template<typename T>
void Foo::bar(T dummy) { }
void Foo::bar(bool dummy) { }
int main()
{
Foo f;
f.bar('a');
f.bar(true);
}
Upvotes: 0
Reputation: 55897
Function template can not be partially specialized, but can be explicitly specialized, your code is perfectly correct.
Upvotes: 2