Explicit Template Function and Method Specialization

冷暖自知 提交于 2019-12-10 23:18:29

问题


I've been looking for a clear answer, and I'm just catching bits and pieces from the web.

I've got a function, and it needs to act differently based on a type variable. The function takes no arguments, so overloading doesn't work, leading to template specialization. E.g.:

//Calls to this function would work like this:
int a = f();
int b = f<int>();
int c = f<char>();
//...

First off, is that even syntactically possible? I feel like it is. Continuing.

I'm having problems defining this function, because I get hung up on the syntax for explicit specialization. I've tried a number of different approaches, but I have yet to get even a simple example to work.

Secondly, I'm trying to (eventually) make that template function into a template method of a (non-template) class. I'll cross that bridge when I come to it.

Thanks,
Ian


回答1:


Well, it is possible but is not one of the nicer things to do. Explicit template function specializations are somewhat of a dark corner, but here is how you do it:

template< typename T > int f(){ ... }

template<> int f<int>(){ ... }
template<> int f<char>(){ ... }

Some related reading: http://www.gotw.ca/gotw/049.htm




回答2:


First off, is that even syntactically possible? I feel like it is.

It is, but don't over-complicate things – this only needs simple overloading:

int f()
{
    return /* default, typeless implementation */;
}

template<typename T>
int f()
{
    return /* type-specific implementation */;
}

template<>
int f<char>()
{
    return /* char implementation */;
}

template<>
int f<int>()
{
    return /* int implementation */;
}


来源:https://stackoverflow.com/questions/10645738/explicit-template-function-and-method-specialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!