Mic*_*ael 3 c++ templates specialization
我有一个关于C++模板专业化的问题,我希望有人可以提供帮助.我有一个有3个模板参数的类:
template<class A, class B, class C>
class myClass {
public:
void myFunc();
};
Run Code Online (Sandbox Code Playgroud)
我想要做的是写几个版本的myFunc,专门用于比如C,但是对于类型A和B是通用的.所以我不想要这样的完全模板化的函数:
template<class A, class B, class C>
void myClass<A, B, C>::myFunc()
{
// function code here
}
Run Code Online (Sandbox Code Playgroud)
我不想要像这样的完全专业化的功能
void myClass<int, int, int>::myFunc()
{
// code goes here
}
Run Code Online (Sandbox Code Playgroud)
相反,我想做一些类似的事情
template<class A, class B>
void myClass<A, B, int>::myFunc()
{
// code goes here
}
Run Code Online (Sandbox Code Playgroud)
我的想法是,如果类类型C是int,我会调用myFunc()的一个版本,如果类类型C是double,我会调用不同版本的myFunc.我已经尝试了很多模板特化语法的差异组合(这里列出的太多了),似乎没有编译.
有人可能会指出我在正确的方向吗?在此先感谢您的帮助.
迈克尔
您可以编写函数模板和重载,并将工作委托给它:
template<class A, class B, class C>
class myClass
{
//resolver doesn't need to define anything in it!
template<class> struct resolver {}; //empty, yet powerful!
public:
void myFunc()
{
doFun(resolver<C>());
}
//this is a function template
template<typename X>
void doFun(const resolver<X> & )
{
//this function will get executed when C is other than int
//so write your code here, for the general case
}
//this is an overload, not a specialization of the above function template!
void doFun(const resolver<int> & )
{
//this function will get executed when C = int
//so write your code here, for the special case when C = int
}
};
Run Code Online (Sandbox Code Playgroud)
注意重点:doFun(const resolve<int>& )是一个重载函数,它不是函数模板的特化.如果不专门化封闭类模板,则无法专门化成员函数模板.
阅读这些文章:
| 归档时间: |
|
| 查看次数: |
685 次 |
| 最近记录: |