以下简化的情况将在 MSVS 13 中正常编译和运行,但在 gcc 4.9.0 中我得到错误:
cannot convert from
<brace-enclosed initializer list>
tostd::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&
。
另请注意,您正在为 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/