gpt4 book ai didi

c++ - 为什么隐式转换在 g++ 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:59 25 4
gpt4 key购买 nike

下面的代码可以在 Visual Studio 中编译,但在 gcc 中编译失败。

template<typename Isth>
class A
{
public:
A(const boost::shared_ptr<Isth>& obj) {...}
...
};

在B类的方法中:

A<Isth1> B::method1
{
boost::shared_ptr<Isth2> myPtr = boost::make_shared<Isth2>();
//Isth2 is derived from Isth1;
...
return myPtr;
}

在 gcc 中,我得到一个错误“无法将‘myPtr’从‘boost::shared_ptr’转换为‘A’”我认为 A 的构造函数应该在 B::method1 返回时被调用。

提前致谢!

最佳答案

其他人强调了这个问题 - shared_ptr<Isth2>只能转换为A<Isth1>的构造函数参数如果它不需要用户定义的转换。但既然这样做了,就不能使用该构造函数。

统一初始化再次有助于完成这项工作

A<Isth1> B::method1()
{
boost::shared_ptr<Isth2> myPtr = boost::make_shared<Isth2>();
//Isth2 is derived from Isth1;
...
return { myPtr };
}

对于返回值的统一初始化,允许对构造函数参数进行用户定义的转换。如果只想更改类 A , 你可能想写一些 SFINAE

template<typename T, typename std::enable_if<
std::is_base_of<Isth, T>::value, bool>::type = true>
A(const boost::shared_ptr<T>& obj) {...}

您基本上是在声明“我正在从指向从 Isth 派生的对象的任何共享 ptr 隐式转换”

关于c++ - 为什么隐式转换在 g++ 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33788529/

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