问题
In below code snippet while calling call back function "Invalid use of void expression" error is flashed by the compiler.
#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;
}
Just want to know what is the wrong here so that same can be addressed .
回答1:
It seems that you want to pass the Callback<int>
function itself, not its return value (which there is none), to the constructor of obj
. So do just that:
State<int> obj(10, Callback<int>);
Your current code actually calls Callback(10)
first and then tries to take its void
"return value" to pass it to the constructor of obj
. Passing void
is not allowed in C++, which is why the compiler is complaining. (Callback(10)
is the "void expresson" here.)
回答2:
I guess this is what you want
#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;
}
回答3:
I would like to go with lambda expression approach to avoid the confusion :
#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;
}
来源:https://stackoverflow.com/questions/58646851/invalid-use-of-void-expression-in-context-of-c-stdfunction