[英]Can I get rid of template specialisation with std::enable_if?
I read about std::enable_if
for: 我读到了
std::enable_if
:
function overloading based on arbitrary properties of type
基于类型的任意属性的函数重载
So I was trying to overload class ctors via enable_if
(like below) but i get error saying that enable_if
cannot be used to disable declaration and this in both lines when I used std::enable_if
: 所以我试图通过
enable_if
(如下所示)重载类ctors但是我得到错误,说当使用std::enable_if
时, enable_if
不能用于禁用声明和这两行:
#include <iostream>
#include <type_traits>
#include <typeinfo>
template <typename T>
class cls
{
public:
cls (T a, typename std::enable_if< std::is_same<T, int>::value >::type * Dummy = 0)
{
std::cout << "Ctor for int\n";
}
cls (T a, typename std::enable_if< std::is_same<T, char>::value >::type * Dummy = 0)
{
std::cout << "Ctor for char\n";
}
};
int main()
{
cls a(10);
cls b('x');
return 0;
}
So is it possible to overload ctors using enbale_if
. 因此可以使用
enbale_if
重载enbale_if
。
The problem is, eg when you instantiate a cls<int>
, you'll always get a failed requirement from the 2nd constructor overloaing, ie std::enable_if< std::is_same<T, char>::value >::type
with T
is int
. 问题是,例如,当您实例化
cls<int>
,您将始终从第二个构造函数overloaing获得失败的需求,即std::enable_if< std::is_same<T, char>::value >::type
T
是int
。 And it's same for cls<char>
. cls<char>
。
You can make the constructors templates to make SFINAE taking effect; 您可以制作构造函数模板以使SFINAE生效; which will get rid of template specializations from the overload set and won't cause compile error.
这将从重载集中删除模板特化,并且不会导致编译错误。 eg
例如
template <typename X = T>
cls (X a, typename std::enable_if< std::is_same<X, int>::value >::type * Dummy = 0)
{
std::cout << "Ctor for int\n";
}
template <typename X = T>
cls (X a, typename std::enable_if< std::is_same<X, char>::value >::type * Dummy = 0)
{
std::cout << "Ctor for char\n";
}
You don't seem to need enable_if
here, just a regular constructor: 你似乎不需要这里的
enable_if
,只是一个常规的构造函数:
cls(T a) { std::cout << "Ctor for T\n"; }
To disable a template class specialization do not provide its definition: 要禁用模板类专门化,请不要提供其定义:
template<> class cls<void>; // disabled specialization.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.