2015-06-18 14 views
5

經過question關於std::bind後,我想知道是否有可能持有由std::bind創建的功能vector,所以我可以避免使用std::function及其重磅包裝。如何在不存在模板的特定情況下存儲std :: bind的向量?

#include <iostream> 
#include <functional> 
#include <typeinfo> 
#include <vector> 

int add(int a, int b) {return a + b;} 

int main() { 

    //I believe this here is just a special type of bound function. 
    auto add2 = std::bind(add, std::placeholders::_1, 2); 
    auto add3 = std::bind(add, std::placeholders::_1, 3); 

    //Yup. 
    std::cout << typeid(add2).name() << std::endl; 
    //Here's the type of the second function 
    std::cout << typeid(add3).name() << std::endl; 

    //Is there a nicer way to do this? 
    std::vector<decltype(std::bind(add, std::placeholders::_1, 1))> vec; 

    return 0; 
} 

雖然可以創造的std::bind功能的載體,是有辦法,我就不必爲了宣佈一個容器而沒有空/空型提供綁定功能的具體情況由std::bind製作的功能?

+0

爲什麼不'std :: vector vec;'?或者你假設想'安置'每個向量元素? – SU3

+0

我希望能夠初始化而不必提供任何綁定的功能。所以在手之前不要內聯'std :: bind'或綁定函數。 – VermillionAzure

+2

好吧,'bind'返回一個未指定的類型,所以你需要'bind'表達式才能推斷出類型。無論如何,你的'vector'的效用是相當有限的,因爲改變bind表達式中綁定參數以外的任何東西都會改變結果類型,所以你沒有多少選擇'bind'您可以添加到該「矢量」的表情。 – Praetorian

回答

1

因此,看來這是不possible-- std::bind似乎不具有通常可命名/顯式類型 - 根據綁定函數的簽名通常生成的類型,並沒有按似乎不可指定。使用std::function似乎是包裝std::bind函數並將它們存儲在向量中的唯一方法。

Even for lambdas, this doesn't seem possible - 使用std::function形式的包裝似乎是最佳答案,儘管產生的函數對象的大小增加了。

可能的替代方案可能是存儲Functor對象被設計用來模仿與具有類型檢查層的泛型對象的耦合(儘管這看起來很重)。無論如何,使用std::function似乎是最乾淨的解決方案。

0

這個怎麼樣?

#include <iostream> 
#include <functional> 
#include <vector> 

int add(int a, int b) { return a + b; } 

using bound_add_t = decltype(std::bind(add, std::placeholders::_1, int())); 

int main() { 
    std::vector<bound_add_t> vec; 
    vec.emplace_back(add,std::placeholders::_1, 1); 
    vec.emplace_back(add,std::placeholders::_1, 2); 
    vec.emplace_back(add,std::placeholders::_1, 3); 

    for (auto &b : vec) 
    std::cout << b(5) << std::endl; 

    return 0; 
} 
+0

你絕對不能依賴這些'emplace_back's工作。 –

+0

不,對不起,我想要一個真正的解決方案,而不僅僅是一個簡單的「使用」別名。 – VermillionAzure

+1

我只是真的認爲你所要求的是不可能的,如果你想保持可移植性。 'std :: bind'構造函數返回'/ * unspecified * /',所以它依賴於實現。我想,如果你只關注單個編譯器,那麼可能有一個內部模板可以給你類型,但我懷疑調用它會使你的語法更短,然後使用'decltype'。你必須提供一個類型作爲向量的模板參數。你可以在那裏粘貼'auto'或者其他類似的東西。 – SU3

相關問題