2015-10-02 26 views
1

我有这个功能为偏特正确的语法与智能指针

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) { ... } 

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

+1

功能模板不能部分专用。把它作为一个带有静态成员函数的类模板和一个转发给这个类的通用函数模板来写。 – Andrew

+1

@Andrew超载应该足够了(由于部分排序) –

+0

@PiotrSkotnicki确实应该。 – Andrew

回答

1

你不能部分专门的功能模板。但是,您可以放心地依靠您当前的解决方案。 具有两个功能重载:

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>&参数与B一个const Unique&参数推导失败。