在 C++ 中,如果我尝试这样做:
std::function<void(bool,void)>
然后编译器会抛出错误。为什么是这样?它在许多情况下很有用。一个例子:
//g++ -std=c++17 prblm.cpp
#include <cstdio>
#include <functional>
template<class type_t>
class some_callback
{
public:
using callback_t = std::function<void(bool,type_t)>;
some_callback(callback_t _myfunc)
{
this->myfunc = _myfunc;
}
callback_t myfunc;
};
using callback_with_just_bool = some_callback<void>;
using callback_with_an_int_too = some_callback<int>;
int main()
{
auto my_callback_with_int = callback_with_an_int_too([](bool x, int y)
{
}); //OK
auto my_callback_just_bool = callback_with_just_bool([](bool x)
{
}); //Error
auto my_callback_just_bool = callback_with_just_bool([](bool x,void z)
{
}); //Error
return 0;
}
如果用户希望在他们的回调中有选择地拥有额外的数据,这允许一个非常干净的语法,但不是必须的。但是,编译器将拒绝尝试初始化 callback_with_just_bool
为什么会这样,是否有一种干净的解决方法?谢谢。
编辑:在现实世界的代码中,我尝试这样做的具体原因是在事件系统中。向事件系统提供了有关希望有条件地接收事件的单个对象的数据(例如“如果您离源足够近,您将收到一个声音事件”)以及提供给回调的数据关于事件(例如“X200 Y200 处的 10khz 噪声”)。大多数时候,检查要求所需的数据将存在于提供给回调的数据中关于事件,但如果不是这种情况,我想提供一个可选的附加数据结构。因此,如果用户不需要这个额外的数据结构,他们会指定“void”。
最佳答案
“这是为什么?”
因为参数列表中 void
的唯一允许用法是表明该函数不接受任何参数。
来自 [function] :
void
Indicates that the function takes no parameters, it is the exact synonym for an empty parameter list:
int f(void);
andint f();
declare the same function. Note that the type void (possibly cv-qualified) cannot be used in a parameter list otherwise:int f(void, int);
andint f(const void);
are errors (although derived types, such asvoid*
can be used)
“有没有干净的方法解决它?”
我建议专攻void
:
template<class type_t>
class some_callback
{
std::function<void(bool,type_t)> myfunc;
};
template<>
class some_callback<void>
{
std::function<void(bool)> myfunc;
};
关于C++ - 为什么 std::function<some_type_t, void> 无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53452226/