功能专门用于模板

yzz*_*yzz 5 c++ templates template-specialization

我需要使用模板类对我的函数进行专门化,并且遇到"非法使用显式模板参数"的问题.

template <typename T>
class MyClass { /* ... */ }; // it can be any template class, eg std::vector

template <typename T>
void foo() { /* ... */ } // my template function which need a specialization

template<> 
void foo<int>() /* sth special for integers - it works */ }

template<template T> 
void foo<MyClass<T> >() /* sth special for template class with any parameter - it doesnt work :( */ }
Run Code Online (Sandbox Code Playgroud)

当然我可以为我需要的所有MyClass类型输入一些专门化,但也许它可以替换为一个?

hiv*_*ert 5

函数的模板特化不像专业化那样灵活struct:只允许完全特化.如果你想做部分特化,你需要将你的foo函数包装在struct:

template <typename T> class MyClass { };

template <typename T> struct Foo;

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

template<> struct Foo<int> { void foo() { } };

template<typename T> struct Foo< MyClass<T> > { void foo() {} };
Run Code Online (Sandbox Code Playgroud)

而不是打电话

foo<MyClass<...>>()
Run Code Online (Sandbox Code Playgroud)

你打电话

Foo< MyClass<...> >::foo()
Run Code Online (Sandbox Code Playgroud)