模板构造函数优先于普通复制和移动构造函数? [英] Template Constructor Taking Precedence Over Normal Copy and Move Constructor?

查看:72
本文介绍了模板构造函数优先于普通复制和移动构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序的输出...

The output of the following program...

#include <iostream>

using namespace std;

struct X
{
    X(const X&)              { cout << "copy" << endl; }
    X(X&&)                   { cout << "move" << endl; }

    template<class T> X(T&&) { cout << "tmpl" << endl; }
};

int main()
{
    X x1 = 42;
    X x2(x1);
}

tmpl
tmpl

所需的输出为:

tmpl
copy

为什么具体的复制构造函数不优先于模板构造函数?

Why doesn't the concrete copy constructor take precedence over the template constructor?

总有办法修复它,以便复制并移动

Is there anyway to fix it so that the copy and move constructor overloads will take precedence over the template constructor?

推荐答案

选择构造函数时,正常的重载解析规则仍然适用-构造函数采用与采用const左值引用的构造函数相比,非const左值引用(对于在扣除参数后的模板构造函数而言)是更好的匹配。

Normal overload resolution rules still apply when choosing the constructor - and a constructor taking a non-const lvalue reference (for the template constructor after argument deduction) is a better match than a constructor taking a const lvalue reference.

当然,您可以添加另一个采用非常量左值引用的重载,即

You could, of course, just add another overload taking a non-const lvalue reference, i.e.

X(X&)              { cout << "copy" << endl; }

更新:模板构造函数更匹配的其他情况:

Update: Other cases where the template constructor is a better match:

const X f()
{ return X(); }

struct Y : X
{ Y() { } };

int main()
{
  X x3(f()); // const-qualified rvalue
  Y y;
  X x4(y); // derived class
}

这篇关于模板构造函数优先于普通复制和移动构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆