【问题标题】:In-class member initializer fails with VS 2013VS 2013 的类内成员初始化程序失败
【发布时间】:2014-07-01 19:49:23
【问题描述】:

我希望下面的代码能够编译,但 Visual Studio 2013 Update 2 给了我一个错误,而 g++ 4.7 可以很好地编译它。

using std::vector;
using std::string;

struct Settings
{
    vector<string> allowable = { "-t", "--type", "-v", "--verbosity" };
};

VS 2013 编译失败:

'std::vector&lt;std::string,std::allocator&lt;_Ty&gt;&gt;::vector' : 没有重载函数需要 4 个参数

如果我按如下方式更改成员,那么它可以正常编译:

vector<string> allowable = vector<string> { "-t", "--type", "-v", "--verbosity" };

我查看了从 Bjarne 的 FAQ 链接的 proposal 并查看了 MSDN page 中有关 VS 2013 中已完成的 C++11 功能的内容,但我仍然感到困惑。它应该按原样编译,还是我错了,必须两次指定类型?

【问题讨论】:

  • initializer_list 在 MSVC 2013 上被严重破坏了,事实上很多 C++11 的特性对于它们是否工作来说都是一个死机:(

标签: c++ visual-c++ c++11 visual-studio-2013 initializer-list


【解决方案1】:
  • 您展示的示例是完全有效的 C++,但它不适用于 VC++2013。

  • 这是自 2013 年 10 月 31 日以来报告的已知 VC++2013 bug,其状态仍然有效。

  • 但是,您可以通过解决方法来克服它。正如@ildjarn 建议的那样,只需添加一对额外的花括号,就可以强制调用std::vectorinitializer_list&lt;&gt; 构造函数而不是其填充构造函数,如下例所示:


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

   struct Settings {
     std::vector<std::string> allowable = {{"-t", "--type", "-v", "--verbosity"}};
   };

   int main() {
     Settings s;
     for (auto i : s.allowable) std::cout << i << " ";
     std::cout << std::endl;
   }

【讨论】:

  • 因为在调用构造函数时就好像使用了括号而不是大括号,所以可以简单地使用第二组大括号来强制调用 initializer_list&lt;&gt; 构造函数。所以std::vector&lt;std::string&gt; allowable = {{ "-t", "--type", "-v", "--verbosity" }}; 是一个更简单的解决方法。 +1 用于查找 Connect 错误。
  • @ildjarn 谢谢老兄,我更正了,您的解决方案更简单,因此更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 2017-02-12
  • 1970-01-01
相关资源
最近更新 更多