Jingcheng Yu
Jingcheng Yu

Reputation: 53

How to specialize a static function of a class template?

When I tried to write something like this:

#include <iostream>

template <class T>
class A
{
public:
    static void doit();
};

template <>
static void A<int>::doit() 
{
    std::cout << "int" << std::endl;
}

template <>
static void A<double>::doit()
{
    std::cout << "double" << std::endl;
}

int main()
{
    A<int>::doit();
    A<double>::doit();
}

I got a compile error: The capture of error message

Specializing the whole class is ok. I just want to know is there any way to specialize only the static function?

Upvotes: 0

Views: 89

Answers (1)

Heavy
Heavy

Reputation: 1900

You should specify static keyword only once, in declaration.

Try this:

template<>
void A<int>::doit() 
{
    std::cout << "int" << std::endl;
}

template<>
void A<double>::doit()
{
    std::cout << "double" << std::endl;
}

Upvotes: 3

Related Questions