Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

c++ - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...