I have this (dumbed down) function template inside a
namespace M
of my own:
On M.h
1 2
|
template <typename var>
void print(int, int, var);
|
On M.cpp (compiling and linking)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
using std::string;
template <typename var>
void M::print(int x, int y, var Text){
/*
Function definition
*/
}
template void M::print<string>(int,int, string);
template void M::print< int >(int,int, int );
template void M::print< char >(int,int, char );
|
The point of it is being able to call for the function print() with either a string, an integer, or a character (and possibly other variables in the future).
This works great. However, when I call for the function expecting it to take a string:
M::print(23,7, "hello");
The compiler takes the text inside quotes as a
const char*
, and not an object of type std::string, giving an error. Now, there are two obvious solutions. One; adding
(string)
behind every quote whenever I want to print a string (Or using a macro such like
#define S (string)
. Two; replacing the template specialization from
string
to
const char*
.
I don't like either solution. The first is ugly and tears down the cleanliness of using templates, and the second defeats the purpose of using std::string's in C++. is there a way to make it take my std:string objects by default? Or which solution would you recommend?
I don't want to use function overloading as it makes me copy and paste the function three times over, and I'm already overloading the template, having a copy of the function that takes an object
coord
of my own as an argument instead of the two int's . That'll be making it a total of 6 copies of the almost same function.