【发布时间】:2016-09-10 08:51:37
【问题描述】:
我正在编写一个类,其中有一个模板构造函数和复制构造函数。每次我想用非 const 对象调用复制构造函数时,都会选择模板化构造函数。如何强制编译器选择复制构造函数?
这里是 mcve:
#include <iostream>
struct foo
{
foo()
{
std::cout << "def constructor is invoked\n";
}
foo(const foo& other)
{
std::cout << "copy constructor is invoked\n";
}
template <typename T>
foo(T&& value)
{
std::cout << "templated constructor is invoked\n";
}
};
int main()
{
foo first;
foo second(first);
}
删除函数不是我想要的。
【问题讨论】:
-
当调用 ctor 时,不应该将参数转换为
const &foo吗? ctor 用于 const args,因此请提供一个。 -
@PeterA.Schneider,我在写
std::variant。我认为人们不会喜欢选角。我想保持用户端干净 -
避免所有这些恶作剧的一种方法是为转发构造函数提供一个虚拟的第一个参数,这样就不会有混淆的可能性
-
这可能有助于更清楚地思考你想要什么。你想禁止所有
T的模板构造函数,就像foo一样吗? (foo&&,foo&,const foo&,volatile foo&,...)。这应该很容易用一点enable_if。或者只是在存在可行的非模板构造函数的特定情况下禁止模板构造函数? (我认为后者是不可能的) -
@M.M,
std::variant支持没有虚拟第一个参数的模板化构造函数。我想写出尽可能严格符合标准的实现。
标签: c++ c++14 copy-constructor