| re: How do I make my convert() function do nothing for equal types?
Eric Lilja wrote:[color=blue]
> I solved it, here it is with the convert() function as a stand-alone
> function:
> template<typename T1, typename T2>
> T2 convert(const T1& a, const T2&)
> {
> stringstream ss;
> ss << a;
>
> T2 out;
>
> if(!(ss >> out))
> throw runtime_error("Conversion not possible.");
>
> return out;
> }
>
> template<>
> std::string convert(const std::string& s, const std::string&)
> {
> return s;
> }
>
> Now, should I (can I?) make convert a member of the class Option? And[/color]
can I[color=blue]
> loose the second argument (it's after all not used in the function)?
>
> / Eric[/color]
You don't need to second argument. In the option class, declare it
like this:
template<typename RETURN_TYPE>
RETURN_TYPE convert(const std::string& s);
Outside the class, provide two definitions for this function, one
generic and the other specialized for std::string:
template <typename TYPE>
template <typename RETURN_TYPE>
RETURN_TYPE Option<TYPE>::convert(const std::string& s)
{
// ...
}
template <typename TYPE>
template <>
std::string Option<TYPE>::convert<std::string>(const std::string& s)
{
// ...
}
When you call the convert function, you call it like this:
convert<TYPE>(s);
So, if 'TYPE' is 'std::string', it will call the specialised version.
Hope this helps,
-shez- |