【问题标题】: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初始化 std::vector<std::function<bool(std::string)>> 的初始化器列表在 g++ 4.9.0 中出现错误,但在 Visual Studio 2013 中编译良好
【发布时间】:2014-09-13 21:33:49
【问题描述】:

以下简化的情况将在 MSVS 13 中编译并运行良好,但使用 gcc 4.9.0 时出现错误:

无法从 &lt;brace-enclosed initializer list&gt; 转换为 std::vector(std::function&lt;bool(std::string)&gt;&gt;

#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;
}

我是不是做错了什么,或者错过了初始化列表应该如何工作的一些内容?

【问题讨论】:

  • @Praetorian,抱歉,我安装编译器的计算机没有连接到互联网,所以我必须手动重新输入示例。
  • 我不认为这是一个最小的例子。或附近的任何地方。

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


【解决方案1】:
template<typename A> bool do_something(std::string& s, A& a, A b, A c)

do_something的第一个参数的类型是std::string&amp;,而不是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&amp;

Live demo


还要注意,您正在复制for 循环中的每个向量元素。您可能希望将其更改为

for( auto& v : my_list)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    相关资源
    最近更新 更多