0

I have a template that inherits from another template, with itself as the second template's template parameter. The inherited template defines a static function:

template<class T> class A
{

public:

    static void foo();
};

template<class T> class B : public A<B>
{

};

Now I want to implement the static function for the class A specialized with B, but with B not specialized. But I can't figure out how to declare the template. I'm not even sure if this is possible. My first try was:

template<class T> void A<B<T>>::foo()
{

}

But this gives the error:

"Nested name specifier 'A<B<T>>::" for declaration does not refer into a class, class template or class template partial specialization"

I've tried different things like adding "template<>" in front but none of those worked. I am able to compile this:

template<> void A<B<int>>::foo()
{

}

As well as this:

template<class T> void A<T>::foo()
{

}

Is this an attempt at partial specialization? My first impression is no (there are no templates with multiple parameters where I want to specialize one of them). Rather, I want to specialize a template with another template that is not specialized. Is this possible, and if so what is the proper syntax?

sweatervest
  • 143
  • 8
  • Thank you, I just corrected. I want to implement the static function for the specialization of A with B, but without specializing B. – sweatervest Feb 08 '17 at 17:00

1 Answers1

0

This is indeed partial specialization. You cannot partially specialize just a method, you must partially specialize the whole class. See this answer. You might try implementing foo in a separate helper struct and partially specializing that struct instead.

Here is an example using a helper struct.

#include <iostream>

template<class T> struct t_helper
{
    static void foo()
    {
        std::cout << "Not B<T>\n";
    }
};

template<class T> class A
{

public:
    static void foo() {
        t_helper<T>::foo();
    }
};

template<class T> class B {};

// Specialize the behavior of A<T>::foo() for all B types
template<class T> 
struct t_helper<B<T>>
{
    static void foo()
    {
        std::cout << "Is B<T>\n";
    }
};

int main()
{
    A<int>::foo();    // Prints "Not B<T>\n"
    A<B<int>>::foo(); // Prints "Is B<T>\n"
    return 0;
}
Community
  • 1
  • 1
François Andrieux
  • 28,148
  • 6
  • 56
  • 87