Re: Template functions and avoiding implicit conversions
tarjei.knapstad@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");
the second argument is implicitly converted to bool and the first
template function is instantiated.
Actually, it should fail to compile because "method" is a string
literal, and it cannot be bound to a reference to non-const object
of type 'std::string'. Only if you declare your 'Add' template
as
... void Add(std::string const& arg, ...
can it be used with a string literal as the first argument.
The possible resolutions I've come up with are:
1. Rename the first function to for instance AddRequired(). I'd like
to avoid this to keep the interface as simple as possible.
2. Require the user to explicitly instantiate a std::string in the
call,
clo.Add<std::string>("method", std::string("invert"));. This is far
too error prone and not really a solution at all.
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).
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]