C++ specialization of template with templated type

I’d like to do a generic function which will be specialized with some types, but I also would like to specialized with templated types, which is not allowed by the compiler.
Is there a way to get around this ?

Ideal not working implementation:

template<class D> class Dummy{public: D val;};
  
template<typename T> T foo();

template<> int foo<int>()
{
  return 0;
}

template<typename D> Dummy<D> foo<Dummy<D>>()
{
  return Dummy<D>{};
}

I get the error non-class, non-variable partial specialization ‘foo<Dummy<D> >’ is not allowed

>Solution :

Is there a way to get around this?

If a someone has a problem X, and the solution is Y, then 99% of the time specializing function templates is Z.

Make the function delegate to something that actually can be specialized any way you want:

template<typename T>
struct FooImpl {
  static void func() = delete; // Deleted default implementation
                               // Need to specialize to be valid
                               // Not strictly required, but gives
                               // more informative errors
};

template<>
struct FooImpl<int> {
  static int func() { return 1; }
};

template<typename T>
struct FooImpl<Dummy<T>> {
  static Dummy<T> func() { return {}; }
};

template<typename T>
T foo() {
  return FooImpl<T>::func();
}

Leave a Reply