简体   繁体   中英

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

Given the generic function foo:

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

I'd like to specialize this function for a type Bar, however, Bar itself has several template arguments itself. I was trying to specialize foo() as follows:

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

However, this does not quite work. Could someone please help me out? Thanks

There ain't no such thing as a partial specialization of a function template. One way around is to delegate to a class template, which can in fact be partially specialized. Something along these lines:

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); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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