我怎么能得到c++更喜欢转换char* string_view而不是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过载转换为模板函数,并为其添加约束,使其在接收到可转换为string_view的类型时具有比bool过载更高的优先级。

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

演示。