【问题标题】:C++ : no matching functionC++:没有匹配的函数
【发布时间】:2017-09-21 16:25:55
【问题描述】:

我正在尝试复制我遇到的问题,但现在代码更早失败了。

到目前为止的代码是:

namespace
{
    // this cannot change either - needs to be static
   static bool imp( const int  a , const int b )
   {
      return a != b ;
   }
}

template < typename KEY , 
           typename VALUE, 
           typename CALLBACK = VALUE(*)( const KEY & ) > class ComplexObject
{
     public :
     ComplexObject( CALLBACK ){} ;
     ///......
     // cannot change that so cannot provide default constructor!!!
     //.... more functions that utilite KEY.VALUE - imagine this is a cache
};

using namespace std::placeholders;  // for _1, _2, _3...

typedef std::function<bool(*)( const int)> myFunctor ; 

class TypeA
{
public:
    TypeA(const int id) : n_id(id) ,  n_co( std::bind( &imp , n_id , _1 ) ) {}
    bool check( const int a, const int id ) ;
private :
    int n_id;
    ComplexObject < int, bool, myFunctor > n_co ;
protected :
     TypeA() : n_id(0) , n_co( std::bind( &imp , n_id , _1 )) { }
};

here

错误是:

g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In constructor 'TypeA::TypeA(int)':
main.cpp:32:75: error: no matching function for call to 'ComplexObject<int, bool, std::function<bool (*)(int)> >::ComplexObject(std::_Bind_helper<false, bool (*)(int, int), int&, const std::_Placeholder<1>&>::type)'
     TypeA(const int id) : n_id(id) ,  n_co( std::bind( &imp , n_id , _1 ) ) {}

【问题讨论】:

  • 宁可使用std::function
  • 你能举个例子吗?由于我的其余实现,我需要使用 std::bind。
  • 我不明白你为什么需要它。您应该使用适当的 std::function 和 require 参数类型作为构造函数参数,而不是模板参数。
  • std::function&lt;bool(*)(const int)&gt; 应该是std::function&lt;bool(const int)&gt;,带有public: ComplexObject( CALLBACK )
  • @ghostrider 默认实现是函数指针而不是std::function,因此* 是必要的。但是*必须从std::function中省略

标签: c++ bind functor


【解决方案1】:

std::function&lt;&gt; 模板参数是函数类型,而不是指向函数类型的指针

以下更改修复了它:

typedef std::function<bool(int)> myFunctor;

只有在 C++17 中你可以使用std::function&lt;bool(*)(int)&gt;

【讨论】:

  • 确实如此,但随后,其余代码(此处不可见)将失败。原因是我的 ComplexObject 中的 CALLBACK 需要一个 VALUE()( const KEY & ) - 因此是 bool() 。
  • 你能解释一下为什么 typedef 中的这个更改可以修复它,因为我不明白 :)
  • @ghostrider 为你更新了答案。
猜你喜欢
  • 2021-09-21
  • 2016-11-23
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 2014-11-03
相关资源
最近更新 更多