c++ - Visual Studio 给出了关于模棱两可的 ctor 的错误

标签 c++ visual-c++ visual-studio-2013

我在 VS 2013 中遇到了编译器错误,我的自定义类存在歧义错误,但它可以正常工作 std::vector

#include <initializer_list>
#include <vector>

using namespace std;

class MyArray
{
public:
    std::vector< int > values;
    MyArray(int s) : values(s) { }
    MyArray(std::initializer_list< int >list) { values = list; }
};

int main ()
{
    vector<int> vx({9,8,7}); // Works
    MyArray mx({9, 8, 7});   // Works

    vector<int> vy({9});     // Works
    MyArray my({9});         // VS-compiler complains about ambiguity
    MyArray mz(std::initializer_list<int>{9}); // Works
}

当然,我可以通过显式添加类型来解决歧义:MyArray my(std::initializer_list<int>{9}) ,但是这样很不方便。 有没有一种方法可以对构造函数进行编码,以便 VS 不会提示我的类存在歧义?

std::vector不会出现歧义错误,这似乎应该是可能的。

最佳答案

看来是MS VC++ 2013编译器的bug。

根据 C++ 标准(13.3.1.7 通过列表初始化进行初始化,p.#1)

— Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument.

— If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.

因为在您的类中找到了这样的构造函数,所以应该调用它。

至少这段代码是用 GCC 编译的。

您可以向 Microsoft 编写缺陷报告。通常他们会建议一种解决问题的方法。 不要忘记测试项目的 MS 语言扩展代码。

关于c++ - Visual Studio 给出了关于模棱两可的 ctor 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25088827/

相关文章:

python - 为 Python 3.5 构建 Fortran 扩展或为 2.7 构建 C 扩展

c++ - 使用 Code::Blocks GNU 编译器编译多线程代码

assembly - 有人知道 "mov edi,edi "是做什么的吗?

c++ - 从另一个 dll 链接动态 dll 会导致错误

java - 使用适用于 Java 的 Visual Studio 2013

c++ - CMake:什么是可能的目标源类型,它们可以扩展吗?

c++ - 在测试用例中使用 gtest 特定参数

c++ - Visual Studio 平台工具集与 Windows SDK

visual-c++ - Visual C++ 11 在 CMake 生成的项目中找不到 Boost unit_test_framework 库

less - Visual Studio 浏览器链接 + Chrome 开发者工具