Template specialization for fundamental types

て烟熏妆下的殇ゞ 提交于 2019-12-08 17:45:23

问题


Is there any way to make a template specialization for fundamental types only? I have tried to do the following:

template<typename T, typename = typename std::enable_if<!std::is_fundamental<T>::value>::type>
class foo
{
}

template<typename T, typename = typename std::enable_if<std::is_fundamental<T>::value>::type>
class foo
{
}

But I'm getting an error that the template is already defined.


回答1:


Here you are creating two templated classes with the same name, not specializations.

You need to create a generic one and then specialize it:

// not specialized template (for non-fundamental types), Enabler will 
// be used to specialize for fundamental types
template <class T, class Enabler = void>
class foo { };

// specialization for fundamental types
template <class T>
class foo<T, std::enable_if_t<std::is_fundamental<T>::value>> { };


来源:https://stackoverflow.com/questions/45244809/template-specialization-for-fundamental-types

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