开发者

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 开发者_StackOverflow中文版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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜