Partial specialization of a method in a templated class

拈花ヽ惹草 提交于 2019-11-28 10:45:23

Partial specialization is explicitly permitted by the standard only for class templates (see 14.5.5 Class template partial specializations)

For members of class template only explicit specialization is allowed.

14.7 (3) says:

An explicit specialization may be declared for a function template, a class template, a member of a class template or a member template. An explicit specialization declaration is introduced by template<>.

So any definition starting with

template<typename T>  

is not an allowed syntax for member of class template specialization.

[edit]

As to SFINAE attempt, it failed because actually there are neither overloads nor specializations here (SFINAE works while defining a set of candidate functions for overload resolution or while choosing proper specialization). what() is declared as a single method of class template and should have a single definition, and this definition should have a form:

template<typename T, typename Q> 
B<T,Q>:: bool what(){...}

or may be also explicitly specialized for particular instantiation of class B:

template<> 
B<SomeParticularTypeT,SomeParticularTypeTypeQ>:: bool what(){...}

Any other forms are syntacticaly invalid, so SFINAE can't help.

Why not just change it to..

template<typename T, typename Q> 
struct B : public A 
{   
   bool what()
   {
      return false; //Or whatever the default is...
   }
}; 

template<typename Q>
struct B<float, Q> : public A 
{   
   bool what()
   {
      return true;
   }
}; 

Two possible solutions depending on your use case:

  1. Flexible implementation classes: One problem with your method is that there is a lack of flexibility in the types - no more than true or false type. Based on this excellent CppCon talk(Slide 77), I wrote up this solution by delegating the work to another implementation specific class template. You can see and run this code here. The drawback to this method is that I can't access the rest of the class members but they can be passed in.
  2. Manipulating Enable If: I haven't fully understood why your enable_if solution didnt work but here is mine and it is working. It allows you to partially specialize within the class itself.

P.S. I'm trying to add the code here directly but there is some formatting problem. If someone could help me out with adding the formatted code from Coliru it'd be great.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!