dimanche 7 novembre 2021

C++ conditional execution depending on the type

I have a template function that should execute different code, depends on the type. The simplified function looks like this:

template<typename T>
std::string test(T value)
{
    std::string v;
    if(std::is_arithmetic<T>())
    {
        v = std::to_string(value);
    }
    else
    {
       v = std::string(value);
    }
    return v;
}

Usage:

test("Hello");
test(123);

But I get this error:

In instantiation of void test(T) [with T = const char*]:
error: no matching function for call to to_string(const char*)
note: candidate: std::string std::__cxx11::to_string(int) <near match>
to_string(int __val)

and the same for the following:

to_string(unsigned __val)
to_string(long __val)
to_string(unsigned long __val)

Ok, I understand that in case of, for example const char * the compilation will fail since there is no std::to_string(const char *). but how can I do the code works? Just have to note that in my real code I limit to c++11.

Aucun commentaire:

Enregistrer un commentaire