繁体   English   中英

使用智能指针的部分专业化的正确语法

[英]Correct syntax for partial specialization with smart pointers

我有这个功能

template<class A, class B>
std::shared_ptr<A> Foo(const B& obj) { ... }

我想提供一个方便的功能,该功能也可以获取智能指针( shared_ptrunique_ptr )而不是引用。 像这样:

template<class A, class B>
std::shared_ptr<A> Foo(const std::shared_ptr<B>& obj) {
  return Foo<A>(const_cast<const B&>(*obj));
}

只有当我重载Foo来获取shared_ptr作为参数时,它的工作方式才这样。 但是,我想将其编写为部分专业化知识。 我也试过

template<class A>
template<class B>
std::shared_ptr<A> Foo(const std::shared_ptr<B>& obj) { ... }

此部分专业化的正确语法是什么?

您不能部分专门化功能模板。 但是,您可以放心地使用当前的解决方案。 有两个函数重载:

template<class A, class B>
std::shared_ptr<A> Foo(const B& obj);

template<class A, class B>
std::shared_ptr<A> Foo(const std::shared_ptr<B>& obj);

由于部分排序,编译器认为后者在重载解析方面更加专业 *,因此,只要将匹配的std::shared_ptr<T>作为参数传入,就会选择后者。


* const std::shared_ptr<B>&比更专门const B&因为对于一些独特型UniqueBconst B&可以从推导出const std::shared_ptr<Unique>&的,但在一个计数器的情况下,对于一个const std::shared_ptr<B>&带有参数const Unique&的参数推导B失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM