簡體   English   中英

將mem_fun存儲在標准容器中

[英]storing mem_fun in a standard container

有沒有辦法創建一個vector< mem_fun_t< ReturnType, MyClass > >

我看到的錯誤是:

error C2512: 'std::mem_fun1_t<_Result,_Ty,_Arg>' : no appropriate default constructor available

我真的不明白為什么它不起作用,但它實際上是一個非常難看的解決方案。 只需使用vector<function<ReturnType(MyClass*)>>並且不存在C ++ 03綁定器中存在的那些問題。

你當然可以創建這樣的矢量。

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

struct MyClass
{
    int a()  { return 1; }
    int b()  { return 2; }
};

int main()
{
    std::vector<std::mem_fun_t<int, MyClass> > vec;
    vec.push_back(std::mem_fun(&MyClass::a));
    vec.push_back(std::mem_fun(&MyClass::b));
    MyClass x;
    for (size_t i = 0; i != vec.size(); ++i) {
        std::cout << vec[i](&x) << '\n';
    }
}

如果遇到問題,請仔細閱讀錯誤消息。 例如, std::mem_fun可以返回各種包裝器,具體取決於您傳遞給它的內容。

或者實際上,切換到boost或C ++ 0x的function


編輯:使用此特定錯誤消息,我假設您正在執行調用包含類型的默認構造函數(例如, resize或使用向量的構造函數指定大小)。 您無法使用這些功能。

mem_fun_t滿足要存儲在容器中的要求(它是可復制構造和可分配的),所以答案是肯定的。

但是,它不是默認構造或可比較的,所以有些東西你不能用它們的容器做,包括:

  • 調整大小,除非您提供值填充
  • 使用非零大小構造,除非您提供要填充的值
  • 比較容器

您看到的錯誤來自嘗試調整大小或使用大小構造。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM