2013-05-18 49 views
1

我试图使用旧bind2nd函数以这种方式:C++函数对象结合

template<typename T> 
class printer 
{ 
public: 
    void operator()(T a, string& kd) 
    { 
     cout<<a<<endl; 
    } 
}; 


int main(int argc, char *argv[]) 
{ 
    string nme = "J-dar"; 
    auto f1 = bind2nd(printer<int>(),nme); 

    //f1(5); 
    return 0; 
} 

,但我得到了很多的错误:

required from here 
error: no type named 'first_argument_type' in 'class printer<int>' class binder2nd  ^
error: no type named 'second_argument_type' in 'class printer<int>' typename _Operation::second_argument_type value;           ^
error: no type named 'second_argument_type' in 'class printer<int>' binder2nd(const _Operation& __x, ^
error: no type named 'result_type' in 'class printer<int>' operator()(const typename _Operation::first_argument_type& __x) const ^
error: no type named 'result_type' in 'class printer<int>' operator()(typename  _Operation::first_argument_type& __x) const ^
required from here 
error: no type named 'second_argument_type' in 'class printer<int>' typedef typename _Operation::second_argument_type _Arg2_type;           

从我可以看到它是正确的,所以我真的不知道发生了什么。^

+1

从我的链接,似乎'std :: ptr_fun'可以节省一些工作在这里。从我的链接去看看http://stackoverflow.com/questions/1418756/how-to-use-bind1st-and-bind2nd – chris

回答

6

首先的:我会建议使用放弃bind1st()bind2nd(),这是过时的C + 11,和一般的C++ 03标准库函数编程过时的支持。

你还是使用C++ 11的​​,因为它似乎你能负担得起的 - 从事实判断出你使用的是auto关键字:

#include <functional> 

// ... 

auto f1 = std::bind(printer<int>(), std::placeholders::_1, nme); 

此说只是为记录,已弃用的std::bind2nd()函数需要一些关于函数调用操作符签名的元数据,并且它期望这些元数据作为函数类中的类型别名提供。例如:

template<typename T> 
class printer 
{ 
public: 

    // These metadata must be present in order for bind1st and bind2nd to work... 
    typedef void result_type; 
    typedef T first_argument_type; 
    typedef string const& second_argument_type; 

    void operator()(T a, string const& kd) const 
//           ^^^^^ // Bonus advice #1: 
//            // This could and should be 
//            // const-qualified 
//        ^^^^^ 
//        Bonus advice #2: why not taking by 
//        reference to const here? ;) 
    { 
     cout<<a<<endl; 
    } 
}; 

上述实现的更简单的方法是使用(也已弃用)类模板std::binary_function作为基类,并让这类模板定义合适的类型别名:

template<typename T> 
class printer : public std::binary_function<T, string const&, void> 
//    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
{ 
public: 
    void operator()(T a, string const& kd) const 
    { 
     cout<<a<<endl; 
    } 
}; 

但是,请再考虑将std::bind1st(),std::bind2nd()以及std::unary_functionstd::binary_function放回抽屉。它们被C++ 11对函数式编程更强大的支持所取代。

+1

。 – chris

+0

@chris:你说得对,我其实只检查了接受的答案;)编辑,谢谢 –

+0

@chris:我选择了一个更彻底的编辑。 'std :: bind()'是正确的路要走,不想太坚持其他解决方案。无论如何感谢 –