构造成对向量时出现编译器错误



请有人帮助解释为什么我在OS X上使用Xcode 5.1编译以下代码时出错。Apple LLVM版本5.1(clang-503.0.40)(基于LLVM 3.4svn)。

我想在下面构造X,把一个成对的向量传给它。

#include <iostream>
#include <string>
#include <vector>
#include <utility>
struct X
{
public:
    typedef std::vector<std::pair<std::string, std::string>> VectorType;
    X(VectorType& params) : m_params(params)
    {
    }
    VectorType m_params;
};
int main(int argc, const char * argv[])
{
    X::VectorType pairs
    {
        { "param-1", "some-string-1"},    // pair 0
        { "param-2", "some-string-2"},    // pair 1
        { "param-3", "some-string-3"},    // pair 2
        { "param-4", "some-string-4"},    // pair 3
        { "param-5", "some-string-5"},    // pair 4
        { "param-6", "some-string-6"},    // pair 5
        { "param-7", "some-string-7"}     // pair 6
    };
    X x
    {
        {pairs[0], pairs[2], pairs[5]}
    };
    return 0;
}

报告的错误为:

/main.cpp:37:7: error: no matching constructor for initialization of 'X'
    X x
      ^
/main.cpp:6:8: note: candidate constructor (the implicit move constructor) not viable: cannot convert initializer list argument to 'X'
struct X
       ^
/main.cpp:6:8: note: candidate constructor (the implicit copy constructor) not viable: cannot convert initializer list argument to 'const X'
struct X
       ^
/main.cpp:11:5: note: candidate constructor not viable: cannot convert initializer list argument to 'VectorType &' (aka 'vector<std::pair<std::string, std::string> > &')
    X(VectorType& params) : m_params(params)
    ^
1 error generated.

您的构造函数应该通过const引用来获取其参数

X(VectorType const & params)
             ^^^^^

否则,您就无法传递临时向量(正如您尝试的那样),因为临时向量无法绑定到非常量左值引用。

X有3个构造函数:

  • 用户定义的一个,它抑制自动默认ctor:

    X(VectorType& params)
    
  • 自动复制ctor和移动ctor:

    X(X&&) noexcept
    X(const X&)
    

自定义对象需要一个lvalue,而不是xvalue或常量对象
您可能希望将ctor拆分为:

X(const VectorType& params) : m_params(params) {}
X(VectorType&& params) : m_params(std::move(params)) {}

相关内容

最新更新