mardi 27 avril 2021

C++ overload resolution with template

I want to have a function that takes a std::string and another that takes anything that is not a std::string.

So I have:

#include <iostream>
#include <string>

void foo(const std::string& str) {
  std::cout << "string version called" << std::endl;
}

template<class T>
void foo(T&& str) {
  std::cout << "template version called" << std::endl;
}

int main() {
    foo(std::string{"hello"});
    return 0;
}

The problem is that the templated version is called instead of the std::string version.

So how can I have a foo function that either takes anything or specifically a std::string?

Aucun commentaire:

Enregistrer un commentaire