c++ - 用于初始化 std::vector<std::function<bool(std::string)>> 的初始化列表在 g++ 4.9.0 中给出错误,但在 Visual Studio 2013 中编译良好

标签 c++ visual-c++ gcc c++11 initializer-list

以下简化的情况将在 MSVS 13 中正常编译和运行,但在 gcc 4.9.0 中我得到错误:

cannot convert from <brace-enclosed initializer list> to 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 对象,它不能绑定(bind)到非 const 左值引用参数。改用这个

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

如果不需要修改参数,另一种选择是将函数参数类型更改为 std::string const&

Live demo


另请注意,您正在为 for 循环中的每个 vector 元素制作拷贝。您可能想将其更改为

for( auto& v : my_list)

关于c++ - 用于初始化 std::vector<std::function<bool(std::string)>> 的初始化列表在 g++ 4.9.0 中给出错误,但在 Visual Studio 2013 中编译良好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24897965/

相关文章:

c++ - 在 Windows VC++ 2010 静态链接下构建 boost + ICU

c++ - 在 VC++ 中使用 try/catch 了解异常类型

c - AVR PROGMEM 读取垃圾而不是字符串

linux - gcc -llibname 和操作系统如何找到 lib 路径?

c++ - 查找目录路径

c++ - QListView & QStandardItemModel 在编辑行之前检查文本

c++ - if 语句在 switch block 中不起作用?

c - 如何使用 Windows API 创建文件?

c++ - 如何在c中为函数指定别名

linux - GCC 安装错误