Re: Template functions and avoiding implicit conversions
On Feb 28, 6:08 am, "Ben Craig" <ben.cr...@gmail.com> wrote:
On Feb 27, 7:56 am, "tarjei.knaps...@gmail.com"
<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");
the second argument is implicitly converted to bool and the first
template function is instantiated.
Why is the first member function a template?
Because he wants to have different types of required options as
well. The two functions are parallel: the first is used if the
user must provide the option, the second if there is a default
value for the option if the user doesn't provide it.
If it's feasible, try
writing the first function as a non-template. Then overload
resolution should see the bool conversion as worse than a const char *
template function.
That would be the case with his code if he was using automatic
type deduction. In fact, he always specifies the target type.
(Given that string literals form a special case, where you
generally want them to behave as something else, he might be
able to add a special overload:
template< typename ValueType >
void
Add( std::string const& arg, char const* defaultValue ) ;
If he only wants this to work for std::string, he can provide a
specialization, but no generic implementation.)
--
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! ]