[英]Correct syntax for partial specialization with smart pointers
I have this function 我有这个功能
template<class A, class B>
std::shared_ptr<A> Foo(const B& obj) { ... }
And I want to provide a convenient function that also gets smart pointer ( shared_ptr
or unique_ptr
) instead of references. 我想提供一个方便的功能,该功能也可以获取智能指针(
shared_ptr
或unique_ptr
)而不是引用。 Something like this: 像这样:
template<class A, class B>
std::shared_ptr<A> Foo(const std::shared_ptr<B>& obj) {
return Foo<A>(const_cast<const B&>(*obj));
}
It only works like that if I overload Foo
to get shared_ptr
as a parameter. 只有当我重载
Foo
来获取shared_ptr
作为参数时,它的工作方式才这样。 However, I want to write it as a partial specialization. 但是,我想将其编写为部分专业化知识。 I also tried
我也试过
template<class A>
template<class B>
std::shared_ptr<A> Foo(const std::shared_ptr<B>& obj) { ... }
What is the correct syntax for this partial specialization? 此部分专业化的正确语法是什么?
You cannot partially specialize a function template. 您不能部分专门化功能模板。 However, you can safely rely on your current solution.
但是,您可以放心地使用当前的解决方案。 Having two function overloads:
有两个函数重载:
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);
the latter is considered by the compiler as more specialized * in overload resolution due to partial ordering, hence, it gets picked whenever a matching std::shared_ptr<T>
is passed in as an argument. 由于部分排序,编译器认为后者在重载解析方面更加专业 *,因此,只要将匹配的
std::shared_ptr<T>
作为参数传入,就会选择后者。
* const std::shared_ptr<B>&
is more specialized than const B&
, because for some unique type Unique
, B
in const B&
can be deduced from const std::shared_ptr<Unique>&
, but in a counter scenario, for a const std::shared_ptr<B>&
parameter with a const Unique&
argument deduction of B
fails. *
const std::shared_ptr<B>&
比更专门const B&
因为对于一些独特型Unique
, B
在const B&
可以从推导出const std::shared_ptr<Unique>&
的,但在一个计数器的情况下,对于一个const std::shared_ptr<B>&
带有参数const Unique&
的参数推导B
失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.