【问题标题】:invalid use of void expression in context of c++ std::function在 c++ std::function 的上下文中无效使用 void 表达式
【发布时间】:2019-10-31 15:40:34
【问题描述】:

在下面的代码 sn-p 中调用回调函数“无效使用无效表达式”错误 由编译器刷新。

#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;
}

只是想知道这里出了什么问题,以便解决问题。

【问题讨论】:

  • 你能从你的编译器复制并粘贴确切的错误信息吗?
  • 错误:无效表达式的使用

标签: c++ callback std-function


【解决方案1】:

您似乎想将Callback&lt;int&gt; 函数本身而不是其返回值(没有返回值)传递给obj 的构造函数。所以就这样做吧:

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

您当前的代码实际上调用 Callback(10),然后尝试将其void“返回值”传递给obj的构造函数。在 C++ 中不允许传递 void,这就是编译器抱怨的原因。 (Callback(10) 是这里的“void expresson”。)

【讨论】:

  • 感谢您的解决方案。它编译得很好,但看起来没有命中函数,因为当我尝试在回调函数中打印时它没有出现在屏幕上。
  • @user2997518 你真的在构造函数中调用了这个函数吗? Callback(type1);
  • 是的,在构造函数内部调用后它现在可以正常工作了。接受您的解决方案。
  • 接受。你现在可能会在那边看到绿色标记?
【解决方案2】:

我想这就是你想要的

#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】:

    我想使用 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;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 2016-07-12
      • 2014-11-05
      • 2023-02-07
      • 2015-06-08
      相关资源
      最近更新 更多