LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Template algorithm for std::vector and std::string (https://www.linuxquestions.org/questions/programming-9/template-algorithm-for-std-vector-and-std-string-830919/)

CartmanYO 09-08-2010 02:50 AM

Template algorithm for std::vector and std::string
 
Hello! For example, I have two functions:
Quote:

void func1(std::string &s)
{
s.clear();
}

void func2(std::vector &v)
{
v.clear();
}
Is there a way to create one template function for both vector and string that would clear them?

johnsfine 09-08-2010 06:11 AM

Quote:

Originally Posted by CartmanYO (Post 4091154)
For example, I have two functions:

Please use CODE tags, not QUOTE tags for the code you post.

Quote:

Is there a way to create one template function for both vector and string that would clear them?
You can make one template function for all classes. That function would work for any classes that have clear() methods and give compile time errors for those that don't.

That is the usual way that templates work in C++.

Code:

template <class Anything>
void func1(Anything &s)
{
  s.clear();
}


Sergei Steshenko 09-08-2010 08:55 AM

Quote:

Originally Posted by johnsfine (Post 4091273)
Please use CODE tags, not QUOTE tags for the code you post.



You can make one template function for all classes. That function would work for any classes that have clear() methods and give compile time errors for those that don't.

That is the usual way that templates work in C++.

Code:

template <class Anything>
void func1(Anything &s)
{
  s.clear();
}


If I understand correctly, your template only covers 'func1' while the OP has two different functions: 'func1', 'func2'.

The problem can, of course, be resolved trivially using a macro, but the OP requested a template solution.

CartmanYO 09-08-2010 09:54 AM

Quote:

Originally Posted by johnsfine (Post 4091273)
Please use CODE tags, not QUOTE tags for the code you post.



You can make one template function for all classes. That function would work for any classes that have clear() methods and give compile time errors for those that don't.

That is the usual way that templates work in C++.

Code:

template <class Anything>
void func1(Anything &s)
{
  s.clear();
}


Thanks, johnsfine. I didn't know that templates make it possible to call methods from "Anything" classes.

Sergei Steshenko 09-08-2010 09:56 AM

Quote:

Originally Posted by CartmanYO (Post 4091482)
Thanks, johnsfine. I didn't know that templates make it possible to call methods from "Anything" classes.

The class is not "Anything"; "Anything" is a parameter to be replaced with actual class/type name during instantiation.


All times are GMT -5. The time now is 06:16 PM.