jeudi 25 avril 2019

How do i specialize my template for std::string

I have the following templated function

template <typename As, typename std::enable_if<
std::is_arithmetic<As>::value, As>::type* = nullptr   > 
As getStringAs(const std::string& arg_name)
{
    std::istringstream istr(arg_name);
    As val;
    istr >> val;
    if (istr.fail())
        throw std::invalid_argument(arg_name);
    return val;
}

And i would like to use it like this:

getStringAs<float>("2.f");

What would be a good way to specialize the function for std::string so that i can write

getStringAs<std::string>("2.f");

I have tried all my known ways but they all seem to fail due to the ambiguity generated by the default type of the enable_if. For example: if i write:

template<>
std::string getStringAs<std::string>(const std::string& arg_name)
{    
}

This will not match any template overload. If i add a second type, this will generate an ambiguity error. I have tried google-in but the only thing i could find was about tag dispatch but that would make the call ugly on the user side. I was thinking at the very ugly solution of using a macro definition for replacing getStringAs with a dispatch tag.

Thank you!

Aucun commentaire:

Enregistrer un commentaire