Home > database >  How can I get C to prefer casting char* to string_view instead of bool?
How can I get C to prefer casting char* to string_view instead of bool?

Time:10-17

I have a simple program like this:

#include <iostream>
#include <string_view>

class C {
  public:
    void print(std::string_view v) { std::cout << "string_view: " << v << std::endl; }
    void print(bool b) { std::cout << "bool: " << b << std::endl; }
};

int main(int argc, char* argv[]) {
  C c;
  c.print("foo");
}

When I run it, it prints bool: 1

How can I get C to prefer the string_view implicit cast instead of the bool implicit cast?

CodePudding user response:

You can turn the string_view overload into a template function, and add a constraint to it so that it has a higher preference than the bool overload when it receives a type that can be converted to string_view.

#include <string_view>

class C {
  public:
    template<class T>
    std::enable_if_t<std::is_convertible_v<const T&, std::string_view>>
    print(const T& v) { std::cout << "string_view: " << std::string_view(v) << std::endl; }
    void print(bool b) { std::cout << "bool: " << b << std::endl; }
};

Demo.

  • Related