Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ string template no matching function for call to basic_string<char>

I am writing common function to convert type T to string:

  1. when T is numeric type just use std::to_string

  2. when others use stringstream operator <<

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  3. when T is std::string just return T

template <typename Numeric>
string to_str1(Numeric n){
    return std::to_string(n);
}

template <typename NonNumeric>
std::string to_str2(const NonNumeric& v){
    std::stringstream ss;
    ss << v;
    return ss.str();
}

// if T is string just return
std::string to_str2(const std::string& v){
    return v;
}

template<typename T>
string to_str(const T& t){
    if(std::is_integral<T>::value){
        return to_str1(t);
    }else{
        return to_str2(t);
    }
}

test usage:

int a = 1101;
cout << to_str(a) << endl;

string s = "abc";
cout << to_str(s) << endl;  // should use to_str2(const std::string& v),but compile error

but compile error:

In instantiation of string to_str1 ….. no matching function for call to to_string(std::__cxx11::basic_string

I don’t know why this error, ?

>Solution :

When you write

if(std::is_integral<T>::value){
    return to_str1(t);
}else{
    return to_str2(t);
}

Then it is true that the if condition is either always true or always false at runtime, but it is still required that the two branches can be compiled. The first branch however doesn’t work with T = std::string.

If you want to exclude branches from being compiled completely (aside from syntax check) based on a compile time constant, then you can use if constexpr:

if constexpr(std::is_integral<T>::value){
    return to_str1(t);
}else{
    return to_str2(t);
}

This tells the compiler to check the if condition at compile-time and only compile the branch that would be taken.

This requires C++17 or later.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading