如何在C ++ 11中优雅地解决歧义声明?

问题描述 投票:0回答:1
struct A
{
    A(int) {}
    A(std::initializer_list<int> il) {}
};

template<typename T>
struct B
{
    B(A) {}
    B(std::initializer_list<T>) {}
};

int main()
{
    int n{};
    B   m1(A{n}); // error: call A::A(std::initializer_list<int>)
    B   m2(A(n)); // error: just a function declaration: B m2(A n);
}

如上面的代码所示,我想调用B::B(A(int))来构造类B的对象。我有两个选择:

  1. B m1(A{n});
  2. B m1(A(n));

根据C++ Core Guidelines,首选第一个。

但是,B m1(A{n});将调用A::A(std::initializer_list<int>)而不是A::(int),这不是故意的。因此,我必须使用B m1(A(n));,但这只是一个函数声明:B m2(A n);

如何在C ++ 11中优雅地解决歧义声明?

c++ c++11 standards variable-declaration function-declaration
1个回答
0
投票

您可以为参数A(n)添加另一个括号。

© www.soinside.com 2019 - 2024. All rights reserved.