【发布时间】:2021-03-06 07:17:45
【问题描述】:
我有一个模板类,它以 std::function 作为参数。
在类中,我需要一个返回 bool 的成员函数。
如果 cbFunctionT 返回 bool,函数应该返回它。 如果 cbFunctionT 返回任何其他值(或为 void),则该函数应返回 false。
预计我需要为此使用 std::enable_if。
问题是如何检查 cbFunctionT 是否返回 bool。 在下面的代码中,我使用 std::is_same 作为我要查找的占位符。
template<typename cbFunctionT>
class CallBack
{
template<typename T = cbFunctionT
typename std::enable_if_t<std::is_same<T,bool>::value>* = nullptr>
bool funct()
{
return cbFunctionT();
}
template<typename T = cbFunctionT>
bool funct()
{
return false;
}
}
【问题讨论】:
-
也许将整个模板专门用于
std::function<bool (Args...)>? -
您的意思是完全正确
bool?const bool可以接受吗?bool&?可以隐式或显式转换为bool的东西? -
您的意思是说您想调用类型为
cbFunctionT的std::function成员,可能称为cbFunction?这段代码看起来每次都会返回false,因为它测试cbFunctionT是bool和bool()是false。
标签: c++ templates std-function