2

I feel like I have tried all possible permutations of syntaxes, but I'm not able to make the following code compile, even though what I'm trying to achieve is pretty straightforward: I want the template class method to behave differently if the class is specialized in a certain way. I think this snippet is self-explanatory:

#include <iostream>

template<class F, class T = void>
struct A {
   void foo();
};

template<class F, class T>
void A<F,T>::foo()
{
   std::cout << "two\n";
}

template<class F>
void A<F,void>::foo()
{
   std::cout << "one\n";
}

int main() {
   int tmp = 0;
   A<double, double> a;
   a.foo();
   A<int> b;
   b.foo();

   return 0;
}

I have perused the numerous questions about template specialization on stackoverflow, and that helped me get this far. At this point I feel like this should compile, and have no idea what the right syntax could be.

blue
  • 2,683
  • 19
  • 29
  • 7
    Not possible. You can only partially specialize the entire class template, not just a member function. – T.C. Jul 27 '15 at 17:53
  • IIRC you cannot provide partial member template specializations, but need fully deduced specializations to be resolved correctly by the compiler. – πάντα ῥεῖ Jul 27 '15 at 17:54
  • @T.C. thanks, I thought what I was trying to do was fairly unambiguous but I guess there might be corner cases where it becomes a mess – blue Jul 27 '15 at 17:57
  • If possible you can make a free function and specialize that (or create overloads, which is usually easier) and call that from the member function template. – SirGuy Jul 27 '15 at 17:58
  • `main.cpp:15:17: error: nested name specifier 'A::' for declaration does not refer into a class, class template or class template partial specialization` -- the clang error message seems pretty clear. `A` is neither a class, a class template, or a class template partial specialization. – Yakk - Adam Nevraumont Jul 27 '15 at 17:59

0 Answers0