“模拟”部分功能模板的专业化?

问题描述

我知道部分模板专门化不适用于函数。但是有什么办法可以达到类似的目的吗?我的用例很简单,但是我不确定解决它的最佳方法是什么。

假设我正在编写一个接受STL容器的函数

template<typename T>
void doSomething(T& container) {
    // do something here
}

现在,当传入std::forward_liststd::list时,我希望对此函数使用不同的定义。

起初我以为我可以像这样重载函数

// overload for std::list
template<typename T>
void insertionCppStl(std::list<T>& container) {
    // do SEOmthing here for list
}

但这意味着我也需要为std::forward_list做同样的重载。一点都不理想。

有什么方法可以针对两种不同的输入类型重载函数吗?寻找C ++ 17的答案,但也欢迎C ++ 20的答案。

解决方法

不是很好的解决方案,但是...

template <template <typename...> class C,typename T>
std::enable_if_t<std::is_same_v<C<T>,std::list<T>>
              || std::is_same_v<C<T>,std::forward_list<T>>>
    insertionCppStl (C<T> & container) {
    // do seomthing here for list
}

(警告:代码未经测试)

如丹尼尔·兰格(Daniel Langr)所指出的(谢谢!),该方法仅适用于具有标准分配器的列表,因此对于std::list<T>std::forward_list<T>,而不是std::list<T,A>std::forward_list<T,A>,其中{ {1}}是不同于A的分配器。

根据您的需求,这对您来说是否足够?

更通用的解决方案也可以考虑分配器

std::allocator<T>

显然,这仅适用于template <template <typename...> class C,typename T,typename A> std::enable_if_t<std::is_same_v<C<T,A>,std::list<T,A>> || std::is_same_v<C<T,std::forward_list<T,A>>> insertionCppStl (C<T,A> & container) { // do seomthing here for list } std::list

正如Barry在评论中指出的(谢谢!),当您具有两种(三种,四种...)具有共同点的类型(在这种情况下:具有兼容签名的模板类型)却可以实现类似的解决方案不是一般的解决方案。

不幸的是,我看不到一个简单的通用解决方案...我建议开发一个特定的type_traits来为该函数的特定版本选择可接受的类型。

例如:如果您想要std::forward_liststd::liststd::forward_list s的特定版本,则可以编写如下内容

std::array

然后是template <typename> struct specific_foo : public std::false_type { }; template <typename T,typename A> struct specific_foo<std::list<T,A>> : public std::true_type { }; template <typename T,typename A> struct specific_foo<std::forward_list<T,std::size_t N> struct specific_foo<std::array<T,N>> : public std::true_type { }; 函数的两个版本:特定版本(接收foo()作为第二个参数)和通用版本(接收std::true_type

std::false_type

现在,您需要使用template <typename T> void foo (T const &,std::false_type) { std::cout << "generic version" << std::endl; } template <typename T> void foo (T const &,std::true_type) { std::cout << "specific version" << std::endl; } 的标记分发版本,它可以为第二个参数选择正确的类型

foo()

以下是完整的编译示例

template <typename T>
void foo (T const & t)
 { foo(t,specific_foo<T>{}); }