我怎样才能让 C++ 更喜欢将 char* 转换为 string_view 而不是 bool?

How can I get C++ to prefer converting char* to string_view instead of bool?

我有一个像这样的简单程序:

#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");
}

当我 运行 它时,它打印 bool: 1

如何让 C++ 更喜欢 string_view 隐式转换而不是 bool 隐式转换?

你可以把string_view重载变成模板函数,并且给它加一个约束,让它在接收到一个可以转换的类型时比bool重载有更高的优先级至 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.