gpt4 book ai didi

c++ - 为什么模板构造函数优于复制构造函数?

转载 作者:行者123 更新时间:2023-12-02 09:24:56 24 4
gpt4 key购买 nike

#include <iostream>

struct uct
{
uct() { std::cerr << "default" << std::endl; }

uct(const uct &) { std::cerr << "copy" << std::endl; }
uct( uct&&) { std::cerr << "move" << std::endl; }

uct(const int &) { std::cerr << "int" << std::endl; }
uct( int &&) { std::cerr << "int" << std::endl; }

template <typename T>
uct(T &&) { std::cerr << "template" << std::endl; }
};

int main()
{
uct u1 ; // default
uct u2( 5); // int
uct u3(u1); // template, why?
}

coliru

构造函数的模板重载适合两个声明(u2u3)。但是,当将 int 传递给构造函数时,会选择非模板重载。当调用复制构造函数时,将选择模板重载。据我所知,在重载解析期间,非模板函数始终优于模板函数。为什么复制构造函数的处理方式不同?

最佳答案

As far as I know non-template function is always preferred to template function during overload resolution.

只有当特化和非模板完全相同时才是如此。但这里的情况并非如此。当您调用 uct u3(u1) 时,重载集会获取

uct(const uct &)
uct(uct &) // from the template

现在,由于 u1 不是 const,因此必须应用 const 转换来调用复制构造函数。要调用模板特化,它不需要执行任何操作,因为它是完全匹配的。这意味着模板获胜,因为它更匹配。

要阻止这件事,你可以做的就是使用 SFINAE限制模板函数仅在 T 不是 uct 时调用。这看起来像

template <typename T, std::enable_if_t<!std::is_same_v<uct, std::decay_t<T>>, bool> = true>
uct(T &&) { std::cerr << "template" << std::endl; }

关于c++ - 为什么模板构造函数优于复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57909923/

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