Define a specific case for a template 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 explicitly created it:

  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 completely different function for std :: string

I tried:

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

but it didn’t work.

Any suggestions are welcome,

Thanks Josh

+1
source share
3 answers

If you want to specialize a template, then the syntax is:

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

But, as Neil says, you do not need to specialize this function template; overload will complete the task:

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

Do not use the template at all - just a regular function:

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

It is simply illegal C ++ to specialize a member function of a class template. I think in C ++ 00x this was relaxed. Thorough 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; } 

at compilation

  % 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 
+1
source

Source: https://habr.com/ru/post/1334412/


All Articles