Try to search your question here, if you can't find : Ask Any Question Now ?

Why isn't overload resolution picking the std::vector overload of my template function?

HomeCategory: stackoverflowWhy isn't overload resolution picking the std::vector overload of my template function?
Avatarjulie asked 1 month ago

In the following code I want it to use the std::vector version of f if I call with a std::vector argument, but it’s using the first one and complaining that std::to_string(const std::vector<T>&) doesn’t exist. My understanding of template overload resolution is that it should use the “more specialized” version. Somehow I think that doesn’t apply here because this is a function overload rather than a template overload. But it’s not even using the normal function overload resultion rules, or else it would complain about an ambiguous call to f.

#include <vector>
#include <string>

template<typename T>
std::string f(T&& member) {
    return std::to_string(member);
}

template<typename T>
std::string f(const std::vector<T>& member) {
    return std::to_string(member[0]);
}

int main() {
    int a = 42;
    printf("%sn", f(a).c_str()); // OK

    std::vector<int> b = { 42 };
    printf("%sn", f(b).c_str()); // ERROR: to_string doesn't have a std::vector overload

    return 0;
}

What am I doing wrong?

1 Answers
Best Answer
AvatarFernando answered 1 month ago
Your Answer

8 + 14 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com