功能专业与模板 [英] Function specialized with template
本文介绍了功能专业与模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用模板类专门化我的函数,并且有非法使用显式模板参数的问题。
I need to make a specialization of my function with template class and have problem with "illegal use of explicit template arguments".
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 :( */ }
当然,我可以为我需要的所有MyClass类型键入一些专门化,但也许可以替换为一个?
Of course i can type a few specialization for all MyClass'es which i need to, but maybe it can be replaced with one?
推荐答案
函数的模板特化不像专用化 struct
一样灵活:只允许完全专业化如果你想做部分特化,你需要将你的 foo
结构中的函数:
Template specialization of function is not as flexible as specialization of struct
: only full specialization is allowed. If you want to do partial specialization you need to wrap your foo
function inside a 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() {} };
p>
And then instead of calling
foo<MyClass<...>>()
您呼叫
Foo< MyClass<...> >::foo()
这篇关于功能专业与模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文