gpt4 book ai didi

c++ - 具有通用引用的模板构造函数是否隐藏移动构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:23:40 33 4
gpt4 key购买 nike

这个模板ctor是否隐藏了move ctor?

class A {
public:
template<typename T>
A(T &&t);

// move would be as this:
/*
A(A &&a);
*/
};

那么在这种情况下我应该如何实现 move ctor 呢?它应该使用默认语法 A (A &&) 还是模板特化?

最佳答案

按照标准(草案)

[类.复制]

3 A non-template constructor for class X is a move constructor if its first parameter is of type X&&, const X&&, volatile X&&, or const volatile X&&, and either there are no other parameters or else all other parameters have default arguments (8.3.6). [ Example: Y::Y(Y&&) is a move constructor.

只有非模板构造函数可以是移动构造函数。这同样适用于复制构造函数。因此生成了隐式移动构造函数。

您以通常的方式实现移动构造函数。特化将不起作用,因为隐式非模板移动构造函数是重载决策的首选。

但是,如果参数类型与 const T& 不完全匹配,模板化引用将赢得重载决议。正如 Praveen 的示例所示,这很容易发生。

关于c++ - 具有通用引用的模板构造函数是否隐藏移动构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34942627/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com