tom*_*pps 7 c++ templates sfinae enable-if
我想使用任何整数类型为类创建一个构造函数,但区分有符号和无符号.我不希望它成为类本身的模板.以下不起作用.Visual Studio只是说没有参数匹配.
class Thing{
public:
template<typename Integral>
Thing(
typename std::enable_if<
std::is_integral<Integral>::value &&
!std::is_same<Integral,bool>::value &&
std::is_signed<Integral>::value
,Integral
>::type num
){
//constructor using signed variable as input
}
template<typename Integral>
Thing(
typename std::enable_if<
std::is_integral<Integral>::value &&
!std::is_same<Integral,bool>::value &&
!std::is_signed<Integral>::value//notice this is different
,Integral
>::type num
){
//constructor using unsigned variable as input
}
};
Run Code Online (Sandbox Code Playgroud)
我们需要将SFINAE移动到模板中.如果我们使用
class Thing{
public:
template<typename Integral, typename std::enable_if<
std::is_integral<Integral>::value &&
!std::is_same<Integral,bool>::value &&
std::is_signed<Integral>::value
,Integral>::type* = nullptr> // will fail if type does not exist
Thing(Integral i)
// ^ use Integral type here
{
std::cout << "signed\n";
}
template<typename Integral, typename std::enable_if<
std::is_integral<Integral>::value &&
!std::is_same<Integral,bool>::value &&
!std::is_signed<Integral>::value//notice this is different
,Integral>::type* = nullptr>
Thing(Integral i)
{
std::cout << "unsigned\n";
}
};
int main()
{
int a = 10;
Thing b(a);
unsigned int c = 10;
Thing d(c);
}
Run Code Online (Sandbox Code Playgroud)
我们得到了
signed
unsigned
Run Code Online (Sandbox Code Playgroud)
我也不得不做出的构造public
,因为他们private
在默认情况下.