![](/img/trans.png)
[英]SFINAE or enable_if to check if non-type template parameter is even or odd
[英]SFINAE using std::enable_if: type parameter vs non-type parameter
template<bool F, typename = std::enable_if_t<F>>
auto func1() -> int { return 0; }
template<bool F, typename = std::enable_if_t<!F>>
auto func1() -> int { return 0; }
template<bool F, std::enable_if_t<F, int> = 0>
auto func2() -> int { return 0; }
template<bool F, std::enable_if_t<!F, int> = 0>
auto func2() -> int { return 0; }
这里有两组重载函数: func1()
和func2()
。 func1()
对 SFINAE 使用类型参数,而func2()
对 SFINAE 使用非类型参数。
编译这些函数时, func1()
会导致编译错误,但func2()
不会。 为什么 SFINAE 对func2()
有效而对func1()
失败?
因为在第一种情况下,SFINAE 故障仅删除模板参数的默认值。
// in case F is true, you have
template <bool F, typename = void>
int func1() { return 0; }
template <bool F, typename> // no more default but still available
int func1() { return 0; }
So doesn't disable the function, and you have two definitions of the same function (a default value doesn't change a function signature) so, as pointed by Jarod42 (thanks), you have a violation of the One Definition Rule .
在第二种情况下,您删除了一个模板参数,因此您破坏了 function,因此不再发生冲突。
template <bool F, int = 0>
int func2() { return 0; }
// template<bool F, ...> // function removed
// int func2() { return 0; }
您可以验证,在第一种情况下,“禁用”的 function 仍然可用,使用单个 function 进行测试
template <bool F, typename = std::enable_if_t<F>>
int foo ()
{ return 0; }
并用true
, false
和false, void
调用它。
foo<true>(); // compile: foo<true, void>() called
foo<false>(); // compilation error: no second template paramenter
foo<false, void>(); // compile: explicit second template parameter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.