Skip to content
Advertisement

How to explicitly call the specified overload function?

JavaScript

Like this code, the C++ compiler will convert char* to bool and then call the first function, which is inconsistent with my original intention. Is there any way to prevent the compiler from performing type conversions that I don’t want? Like “-fno-permissive”, but unfortunately, it doesn’t work.

Advertisement

Answer

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:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement