William M. answered 12/22/19
College Professor of C++ with 7+ years of teaching experience
You are basically trying to do a template specialization on ints and std::strings. The way you normally write this is as follows:
#ifndef __FOO_H__
#define __FOO_H__
#include <iostream>
class foo {
public:
foo() = default;
template <typename T>
void doit(const T& t);
};
#endif
template <typename T>
void foo::doit(const T& t) {
std::cout << "foo::do<T> has a " << t << "\n";
}
template <> // template specialization for const std::string&
void foo::doit(const std::string& t) {
std::cout << "foo::do<std::string&> has a " << t << "\n";
}
template <> // template specialization for const int&
void foo::doit(const int& t) {
std::cout << "foo::do<int> has a " << t << "\n";
}
int main() {
foo fs;
fs.doit("what?"); // call std::string& specialization
fs.doit(3); // call int specialization
fs.doit(2.11567); // call main template function
return 0;
}
Note: generally put templated functions and classes in the header file.
See Vandervoorde and Josuttis's book on C++ templates.