Question

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>();
}
Was it helpful?

Solution

Function template can not be partially specialized, but can be explicitly specialized, your code is perfectly correct.

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top