使用模板化类型(嵌套模板类)的部分模板专用化

Partial template specialization, using a templatized type (nested template classes)

本文关键字:专用 类型 嵌套      更新时间:2023-10-16

给定泛型函数foo:

template<typename T> void foo(T a) { a(); }

我想将这个函数专门用于类型 Bar,但是,Bar 本身有几个模板参数。 我试图将 foo(( 专业化如下:

template<typename... Args> void foo<Bar<Args...> >(Bar<Args...> a) { a(42); }

但是,这并不完全有效。有人可以帮我吗?谢谢

不存在函数模板的部分专用化。一种方法是委托给类模板,实际上可以部分专用化。大致如下:

template <typename T>
struct FooImpl {
static void foo(T a) { /* general implementation */ }
};
template<typename... Args>
struct FooImpl<Bar<Args...>> {
static void foo(Bar<Args...> a) { /* special implementation */ }
};
template<typename T>
void foo(T a) { FooImpl<T>::foo(a); }