I want to make a parse function that excludes the type string or char
template <typename T>
bool parse(T & value, const string & token){
istringstream sin(token);
T t;
if( !(sin >>t) ) return false;
char junk;
if( sin >>junk ) return false;
value = t;
return true;
}
How can I do this?
Depending on what you mean by exclude the types
stringorchar. If you want it not to link you can declare but not define specializations for the types:The compiler will see the specialization and not generate the code. The linker will fail as the symbol is not defined in any translation unit.
The second approach, a bit more complicated is not to fail at link time, but to make the compiler not accept the template for those types. This can be done with SFINAE, which is simpler in C++11, but if you need a C++03 solution you can google for it or add a comment:
(I have not run this through a compiler so the syntax might be a bit off, play with it) The compiler will see the template, and when it tries to perform the substitution of the type
Tit will fail due to thestd::enable_if<...>::typenot resolving to a type.In general, what you probably want is to provide different overloads that perform a specific version of the
parseand take precedence:Note that this is not a template, but a regular function. A non-templated function will be a better match than a templated one when the arguments of the call are perfect matches.