2011-12-17 71 views
1

我嘗試編寫一個函數來調用綁定和一些模板的boost函數。所以我有這個主:函數與模板和增強

int  function(char c) 
{ 
    std::cout << c << std::endl; 
    return (0); 
} 

int main() 
{ 
    Function<int (char)> fb = boost::bind(&function, _1); 
    fb('c'); 
    return (0); 
} 

,這是我Function類:

template<typename F> 
class Function 
{ 
private: 
    F  functor; 

public: 
    Function() 
    { 
     this->functor = NULL; 
    }; 

    Function(F func) 
    { 
     this->functor = func; 
    }; 

    template <typename P> 
    void operator()(P arg) 
    { 
     (*this->functor)(arg); 
    }; 

    void operator=(F func) 
    { 
     this->functor = func; 
    }; 
}; 

我有一個問題:當我嘗試編譯,我有這些錯誤:

error C2440: 'initializing' : cannot convert from 'boost::_bi::bind_t<R,F,L>' to 'Function<F>' 
IntelliSense: no suitable user-defined conversion from "boost::_bi::bind_t<int, int (*)(char), boost::_bi::list1<boost::arg<1>>>" to "Function<int (char)>" exists 

有人可以幫我 ?

+1

閱讀關於C++中的Type Erasure。你的類沒有實現它,而C++ 11中的'boost :: function'和'std :: function'實現它。我建議你閱讀這篇文章:http://www.artima.com/cppsource/type_erasure.html – Nawaz 2011-12-17 15:26:56

回答

0

boost::bind將返回未指定的東西,但可轉換爲 boost::function。沒有理由讓你有自己的 function類。

看看這個簡單的例子:

#include <boost/bind.hpp> 
#include <boost/function.hpp> 

int func(char) { return 23; } 

int main() 
{ 
    boost::function<int(char)> bound = boost::bind(func, _1); 
    return 0; 
} 

是什麼unspecified返回類型意味着你的情況?您需要清除Function和 的類型,需要編寫一個名爲AnyFunction的東西。爲什麼?因爲在C++ 03中(甚至C++ 11,例如只接受一個特定的類型作爲函數參數),你將永遠無法詳細說明Function的模板參數的類型。

+0

boost :: function是禁止的,因爲我必須寫一個正在使用'Function f =&function;和'Function fb = boost :: bind(&function,_1);' – 2011-12-17 15:30:16

+0

我不明白。您正在編寫'功能<...>'但其他人已經在使用它?爲什麼不使用'boost :: function'? – pmr 2011-12-17 15:34:12

+0

,因爲這是一個練習,它被禁止使用這個 – 2011-12-17 15:38:30