Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading