我有一个像这样的简单程序:
#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; }
};
演示。