Re: Template functions and avoiding implicit conversions
On Feb 27, 11:28 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
tarjei.knaps...@gmail.com wrote:
Consider the following:
class CommandLineOptions
{
public:
template <typename ValueType>
void
Add(std::string& arg, bool required);
template <typename ValueType>
void
Add(std::string& arg, ValueType default);
};
The problem I have is that if I write something like:
CommandLineOptions clo;
clo.Add<std::string>("method", "invert");
Is there any other neat trick I could use to avoid the implicit
conversion from happening?
But you actually *want* the implicit conversion (from a string literal
to ValueType) here. What you're trying to make your compiler do is
to choose the conversion to ValueType _over_ the conversion to 'bool'.
The conversion to 'bool' is standard, while the conversion to 'string'
is user-defined (however strange might it seem). The compiler has to
choose the standard conversion according to 13.3.3.2/2.
Use 'int' instead of 'bool'. There is no conversion from a string
literal to 'int', and there is from 'bool' to 'int', so you can still
write
clo.Add<std::string>("method", true)
(provided that you const-qualify the first arg's object).
But isn't this just displacing the problem? What happens when
he wants to add an option which takes integer arguments, and has
a default of 42:
clo.Add< int >( "xyz", 42 ) ;
isn't going to call the function he needs.
(If the name of his class is any indication, I think he's going
about it backwards. IMHO, the options should be independant
objects, whose constructors register themselves with the global
object. The global object then just calls the virtual function
in the object when it finds a match. This allows easy handling
of special cases: boolean options, for example, or an option
which is used as an std::ostream. And of course, since each
option is a separate object, it's fairly simple to access it
later, and to test whether it was set or not.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]