![](/img/trans.png)
[英]Bug or not? Visual Studio 2013 preview std::vector initializer list with std::string
[英]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.