问题描述
在下面的代码中,可变参数构造函数被调用了两次。如何在适当的时候获取被调用的复制构造函数,而不是可变参数构造函数的单个参数版本?
In the following code, the variadic constructor is called twice. How can I get the copy constructor to be called instead of the single argument version of the variadic constructor when appropriate?
#include <iostream>
struct Foo
{
Foo(const Foo &)
{
std::cout << "copy constructor\n";
}
template<typename... Args>
Foo(Args&&... args)
{
std::cout << "variadic constructor\n";
}
std::string message;
};
int main()
{
Foo f1;
Foo f2(f1); // this calls the variadic constructor, but I want the copy constructor.
}
推荐答案
其中构造函数是可变的。具有非可变构造函数模板的以下类具有相同的行为:
This actually has nothing to do with the fact that the constructor is variadic. The following class with a non-variadic constructor template exhibits the same behavior:
struct Foo
{
Foo() { }
Foo(const Foo& x)
{
std::cout << "copy constructor\n";
}
template <typename T>
Foo(T&& x)
{
std::cout << "template constructor\n";
}
};
问题是构造函数模板是更好的匹配。要调用复制构造函数,需要进行限定转换,以将非常量值 f1
绑定到 const Foo&
必须添加const限定符)。
The problem is that the constructor template is a better match. To call the copy constructor, a qualification conversion is required to bind the non-const lvalue f1
to const Foo&
(the const qualification must be added).
要调用构造函数模板,不需要转换: T
推导出 Foo&
,在引用折叠( Foo&&&
- > Foo&
),提供参数 x
type Foo&
。
To call the constructor template, no conversions are required: T
can be deduced to Foo&
, which after reference collapsing (Foo& &&
-> Foo&
), gives the parameter x
type Foo&
.
你可以通过提供一个具有非常量引用参数 Foo&
的第二个拷贝构造函数来解决这个问题。
You can work around this by providing a second copy constructor that has a non-const lvalue reference parameter Foo&
.
这篇关于如何获取通过可变参数构造函数调用的复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!