How to explicitly call the specified overload function?
- Convert the argument at call site:
test(std::string(str));
- Take expected address of overload function:
static_cast<void(*)(const std::string&)>(print)(str);
Is there any way to prevent the compiler from performing type conversions that I don't want?
You might add a catch-all overload as deleted: template <typename T> void test(const T&) = delete;
Alternatively, in C++17, you might do the "dispatching" manually:
template <typename T>
void test(const T& t)
{
static_assert(std::is_constructible_v<std::string, T>
|| std::is_convertible_v<T, bool>);
if constexpr (std::is_constructible_v<std::string, T>) {
const std::string& s = t;
printf("s=%s", s.c_str());
} else if constexpr (std::is_convertible_v<T, bool>) {
printf("b=%d", bool(t));
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…