尝试对从其他类型派生的模板化类型使用std::move
语义时遇到问题。这就是我在下面的例子中得到一个错误。
#include <memory>
template <typename T>
class A{
};
template <typename T>
class B:A<T>{
};
int main()
{
std::unique_ptr<B<int> > bar(new B<int>());
std::unique_ptr<A<int> > foo (std::move(bar));
}
错误在定义foo的行上,它是:
In function 'int main()':
17:47: error: no matching function for call to 'std::unique_ptr<A<int> >::unique_ptr(std::remove_reference<std::unique_ptr<B<int> >&>::type)'
显然,非模板化的等效工作正常。
答案 0 :(得分:6)
B
私下继承自A
,因此无法从B
转换为A
。更改为public
继承,您的代码将编译。
template <typename T>
class B: public A<T>{};
// ^^^^^^
在您的示例中,A
的析构函数应该是virtual
,否则当foo
超出范围时您将undefined behavior因为您和&#{0}} #39;将通过delete
尝试B
A *
个实例。
答案 1 :(得分:-1)
问题是我正在使用私有继承。 当我将B的定义更改为: B级:公众 事情正在发挥作用。
我保留其他解决方案仅供记录: 由于缺乏更好的想法,我正在诉诸于此:
std::unique_ptr<A<int> > foo ( (A<int> * ) new B<int>());