explicit specialization of template class member function

痴心易碎 提交于 2019-11-26 15:04:20
Johannes Schaub - litb

It doesn't work that way. You would need to say the following, but it is not correct

template <class C> template<>
void X<C>::get_as<double>()
{

}

Explicitly specialized members need their surrounding class templates to be explicitly specialized as well. So you need to say the following, which would only specialize the member for X<int>.

template <> template<>
void X<int>::get_as<double>()
{

}

If you want to keep the surrounding template unspecialized, you have several choices. I prefer overloads

template <class C> class X
{
   template<typename T> struct type { };

public:
   template <class T> void get_as() {
     get_as(type<T>());
   }

private:
   template<typename T> void get_as(type<T>) {

   }

   void get_as(type<double>) {

   }
};
Gabriel

If one is able to used std::enable_if we could rely on SFINAE (substitution failure is not an error)

that would work like so:

#include <iostream>
#include <type_traits>

template <class C> class X
{
public:
    template <class T, typename std::enable_if< ! std::is_same<double,T>::value>::type * = nullptr > void get_as(){
        std::cout << "get as T" << std::endl;
    }


    template <class T, typename std::enable_if< std::is_same<double,T>::value>::type * = nullptr  > void get_as(){
        std::cout << "get as double" << std::endl;
    }
};


int main()
{

    X<int> d;
    d.get_as<double>();

   return 0;
}

The ugly thing is that, with all these enable_if's only one specialization needs to be available for the compiler otherwise disambiguation error will arise. Thats why the default behaviour "get as T" needs also an enable if.

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