简体   繁体   中英

Define a specific case for a templated function (C++)

So in my .h file I have

template <class T>
void getValue(T *val, int element, int index);

and then in my .cc file I have a function:

template <class T>
void RParser::getValue(T *val, int element, int index)
{

I also have it explicitly instantiated:

    template void RParser::getValue<char>(char *val, int element, std::string subrecName);
    template void RParser::getValue<long long>(long long *val, int element, std::string subrecName);
    template void RParser::getValue<float>(float *val, int element, std::string subrecName);
...

this works but I would like to make a whole different function for std::string

I tried:

template <class std::string>
void RParser::getValue<std::string>(std::string * val, int element, int index)
{

but that didn't work.

Any suggestions would be greatly appreciated,

Thanks, Josh

Don't use a template at all - just an ordinary function:

void RParser::getValue(std::string * val, int element, int index)
{
}

If you want to specialise the template, then the syntax is:

template<> 
void RParser::getValue<std::string>(std::string* val, int element, int index) {}

But as Neil's answer says, you don't need to specialise this function template; an overload will do the job:

void RParser::getValue(std::string* val, int element, int index) {}

It's simply illegal C++ to specialize a template member function of a class. I think in C++00x this has been relaxed. emphasized text

EDIT:

class foo {
    template <typename T> T bar(const T & t){
        return t;
    }

    template <> int bar<int>(const int & t){ 
        return t + 1 ;
    }
};


int main(int c, const char * v[]){
    foo f;
}

when compiling

 % gcc /tmp/foo.cpp
/tmp/foo.cpp:6: error: explicit specialization in non-namespace scope ‘class foo’
/tmp/foo.cpp:6: error: template-id ‘bar<int>’ in declaration of primary template

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