在c++std::函数的上下文中无效使用void表达式

invalid use of void expression in context of c++ std::function

本文关键字:void 无效 表达式 上下文 c++std 函数      更新时间:2023-10-16

在调用回调函数时出现以下代码段中的"无效使用void表达式"错误由编译器闪存。

#include <iostream>
#include <functional>
using namespace std;
template<class type>
class State {
public:
State(type type1,const std::function<void (type type1 )> Callback)
{
}
};
template <class type>
void Callback(type type1 )
{
//Based on type validation will be done here
}
int main()
{
State<int> obj(10,Callback(10));
return 0;
}

只是想知道这里出了什么问题,这样就可以解决同样的问题。

似乎要将Callback<int>函数本身,而不是其返回值(没有(传递给obj的构造函数。所以就这么做吧:

State<int> obj(10, Callback<int>);

实际上,当前代码首先调用Callback(10),然后尝试获取其void"返回值",将其传递给obj的构造函数。C++中不允许传递void,这就是编译器抱怨的原因。(Callback(10)是此处的">空隙表达式"。(

我想这就是你想要的

#include <iostream>
#include <functional>
using namespace std;
template<class type>
class State {
public:
State(type type1,const std::function<void (type)> callback)
{
callback(type1);
}
};
template <class type>
void Callback(type type1 )
{
}
int main()
{
State<int> obj(10, Callback<int>);
return 0;
}

我想使用lambda表达式方法来避免混淆:

#include <iostream>
#include <functional>
using namespace std;
template<class type>
class State 
{
public:
State( type type1, const std::function<void (type type1 )> Callback)
{
Callback(type1);
}
};
int main()
{
State<int > monitor(10,[] ( int fault) {std::cout<<"Any Message"; });
return 0;
}