简体   繁体   中英

Explicit Template Function and Method Specialization

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. Eg:

//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.

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

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 */;
}

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