gpt4 book ai didi

c++ - 强制编译器选择以 const T& 作为参数的复制构造函数

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

我正在编写一个类,其中有一个模板构造函数和复制构造函数。每次我想用非 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);
}

删除函数不是我想要的。

最佳答案

添加另一个构造函数:

foo(foo& other) : foo( const_cast<const foo&>(other))  // for non-const lvalues
{
}
first示例代码中的对象是非常量左值,因此编译器更喜欢 foo(foo&)超过 foo(const &) .前者由模板提供(带有 T=foo& ),因此被选中。

此解决方案涉及为 foo(foo&) 提供(非模板)构造函数。然后将构造委托(delegate)给复制构造函数,方法是将其转换为对 const 的引用

更新,我刚刚意识到 foo模板也将采用右值。这里有很多选项,但我想最简单的方法是为 foo(foo&&) 添加一个委托(delegate)。 , 和上面的类似
foo(foo&& other) : foo( const_cast<const foo&>(other))  // for rvalues
{
}

关于c++ - 强制编译器选择以 const T& 作为参数的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60311936/

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