我得到了这段代码:
template <class FunctionType> class Entry {
std::function<FunctionType> internalFunction;
template<class... Arguments>
auto operator()(Arguments... arguments) -> decltype(internalFunction(arguments...)){
if (std::is_same<decltype(internalFunction(arguments...)), void>::value) {
internalFunction(arguments...);
} else {
auto result = internalFunction(arguments...);
return result;
}
}
};
入口类是std::function
的包装器。它适用于所有返回类型,只有一个异常(exception) - void
。我无法让它工作。我也尝试过 std::is_void
,它不会为 void(...)
类型的函数返回 true。 std::is_same
也是如此。
如何解决这个问题?
最佳答案
return internalFunction(arguments...);
即使 internalFunction
返回 void
也能正常工作
尝试将结果存储在中间对象中是行不通的,因为您不能创建 void
类型的对象,因为它不是对象类型。
你的 if
不起作用,因为 if
是一个运行时条件,编译器仍然需要编译条件的两个分支,所以它们都必须有效C++。
如果您需要创建一个中间结果类型的变量,那么您不能将该代码用于 void
情况。您可以为返回 void
的函数编写部分特化:
template <class FunctionType> class Entry {
std::function<FunctionType> internalFunction;
template<class... Arguments>
auto operator()(Arguments... arguments) -> decltype(internalFunction(arguments...))
{
auto result = internalFunction(arguments...);
return result;
}
};
template <class... ArgTypes> class Entry<void(ArgTypes...)> {
std::function<void(ArgTypes...)> internalFunction;
template<class... Arguments>
void operator()(Arguments... arguments) {
internalFunction(arguments...);
}
};
这对返回 void
的函数不起作用,但对返回 void
的仿函数不起作用,这样做有点困难。
关于c++ - void function(...) 和 void 类型的 std::is_same?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35710392/