选择函数重载的推导指南(或其他解决方案)

问题描述 投票:0回答:1

我有一个重载的函数。其中 2 个重载是

void foo(std::string_view v);
void foo(MyClass m);

其中

MyClass
有一个来自
std::string
的转换构造函数。如何强制呼叫
foo(std::string{})
来呼叫第一个?现在编译时不会出现错误:

错误:重载的“foo(std::__cxx11::basic_string&)”调用不明确

c++ c++17
1个回答
0
投票

您可以使构造函数显式化

struct MyClass {
    explicit MyClass(const std::string&) {}
};

或提出论点

foo(static_cast<std::string_view>(std::string{}));

或将指针投射到函数

static_cast<void(*)(std::string_view)>(&foo)(std::string{});
© www.soinside.com 2019 - 2024. All rights reserved.