簡體   English   中英

用於初始化std :: vector的初始值設定項列表 <std::function<bool(std::string)> &gt;使用g ++ 4.9.0給出錯誤,但使用Visual Studio 2013可以正常編譯

[英]initializer list to initialize std::vector<std::function<bool(std::string)> > gives error with g++ 4.9.0 but compiles fine with Visual Studio 2013

以下簡化的情況將在MSVS 13中編譯並正常運行,但是使用gcc 4.9.0時出現錯誤:

無法從<brace-enclosed initializer list>std::vector(std::function<bool(std::string)>>

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

template<typename F> class Foo
{
public:
    Foo(int a) : wombat(a) {};
    ~Foo() {}

    bool get_result() { return result; }

protected:
    template<typename A> bool do_something(std::string& s, A& a, A b, A c);

    bool result;
    int wombat;
};

template<typename F> template<typename A> bool Foo<F>::do_something(std::string& s, A& a, A b, A c)
{
    if ( a > b && a < c)
    {
        std::cout << s << std::endl;
        return true;
    }
    return false;
}

struct Tim
{
    int age;
    float weight;
};

class Bar : public Foo<Tim>
{
public:
    Bar(int a) : Foo<Tim>(a) {};
    ~Bar() {};

    void do_somethings();
};

void Bar::do_somethings()
{
     Tim t;
     t.age = 15;

     std::vector<std::function<bool(std::string)> > my_list = {
         std::bind(&Bar::do_something<int>, this, std::placeholders::_1, std::ref(t.age), 10, 100)
     };   // Error shows up here

     for( auto v : my_list) { result = v("howdy"); }
}

int main(int argc, char** argv)
{
    Bar b(200);
    b.do_somethings();
    return 0;
}

我是在做錯什么,還是錯過了初始化列表應該如何工作的事情?

template<typename A> bool do_something(std::string& s, A& a, A b, A c)

do_something的第一個參數的類型為std::string& ,而不是std::string 相應地更改std::function的參數類型。

std::vector<std::function<bool(std::string&)> > my_list = ...
//                                        ^

出於同樣的原因,您不能將std::function實例作為v("howdy")調用,因為這涉及構造臨時std::string對象,該對象無法綁定到非const左值引用參數。 改用這個

std::string s("howdy");
for( auto v : my_list) { result = v(s); }

如果不需要修改參數std::string const&則另一種選擇是將函數參數類型更改為std::string const&

現場演示


還要注意,您正在for循環中復制每個矢量元素。 您可能需要將其更改為

for( auto& v : my_list)

暫無
暫無

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

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