【发布时间】:2017-11-28 00:45:42
【问题描述】:
我正在编写一个存储std::function 的模板类,以便以后调用它。这是简化的代码:
template <typename T>
struct Test
{
void call(T type)
{
function(type);
}
std::function<void(T)> function;
};
问题是这个模板不能为void类型编译因为
void call(void type)
变得未定义。
将它专门用于void 类型并不能缓解问题,因为
template <>
void Test<void>::call(void)
{
function();
}
仍然与call(T Type)的声明不兼容。
所以,利用C++ 11的新特性,我尝试了std::enable_if:
typename std::enable_if_t<std::is_void_v<T>, void> call()
{
function();
}
typename std::enable_if_t<!std::is_void_v<T>, void> call(T type)
{
function(type);
}
但它不能用 Visual Studio 编译:
错误 C2039:“类型”:不是“std::enable_if”的成员
你会如何解决这个问题?
【问题讨论】:
-
SFINAE 仅适用于 deduced 模板参数。
标签: c++ c++11 templates sfinae template-specialization