Originally Posted by
Antigloss
I wanna write a template function that accepts any container type (such as vector, set, list) but restricts the element type of the container to be string.
You may achieve this result if you include some code in your method that will only compile with a string type. The code doesn't even need to actually run. Just threatening to run some string-specific code is enough.
Code:
using namespace std;
template<class CONT>
void f(CONT* obj) {
// Trick compiler into requiring that T of CONT<T> is a string.
if (0) {
(void)obj->at(0).substr((string::size_type)0,string::npos);
}
// ...
}
If you try to call f with something whose elements do not respond to substr(size_type,size_type), you should get a diagnostic leading back to the offending code. substr is just an example, of course.
Code:
struct my_string : string {
my_string() = default;
my_string(string s) : string(s) {}
my_string(const char *s) : string(s) {}
};
int main()
{
vector<string> vs {"one", "two", "three"};
f(&vs); // OK
vector<my_string> vm {"one","two","three"};
f(&vm); // OK
vector<double> vd {1,2,3};
f(&vd); // COMPILER ERROR
}