【发布时间】:2016-12-14 12:29:28
【问题描述】:
过去在使用 SFINAE 选择构造函数重载时,我通常使用以下方法:
template <typename T>
class Class {
public:
template <typename U = T, typename std::enable_if<std::is_void<U>::value, int>::type=0>
Class() {
std::cout << "void" << std::endl;
}
template <typename U = T, typename std::enable_if<!std::is_void<U>::value, int>::type=0>
Class() {
std::cout << "not void" << std::endl;
}
};
但是,我刚刚遇到了这个替代方案:
template <typename U = T, typename std::enable_if<std::is_void<U>::value>::type...>
Class() {
std::cout << "void" << std::endl;
}
考虑到以下内容是非法的......
template <typename U = T, void...> // ERROR!
Class() { }
...上面使用省略号而不是非类型模板参数的替代方法如何工作?
【问题讨论】:
-
@peppe 但是
template<typename U = T, void>也是非法的。那不需要使用void作为类型参数的默认参数吗?如template <typename U = T, typename V = std::enable_if<...>::type>? -
@peppe 作为模板 type 参数,而不是作为模板非类型参数。
-
@Barry: IOW
template<typename std::enable_if<condition>::type>是非法的,因为如果condition为真,它会推断出void,因为这是一个非类型参数,而template<typename std::enable_if<condition, int>::type>是合法的?
标签: c++ c++11 variadic-templates sfinae