Skip to content
Advertisement

How to explicitly call the specified overload function?

#include <cstdio>
#include <string>
constexpr char str[] = "/home/qspace/etc/client/mmkvcfgsvr_test_byset_cli.conf";

void test(bool a)
{
    printf("b=%d",a);
}

void test(const std::string& s){
    printf("s=%s",s.c_str());
}
int main()
{
  test(str);
  return 0;
}

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:

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));
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement