Can a compilation error be forced if a string argument is not a string literal?

前端 未结 7 1936
说谎
说谎 2020-12-17 20:24

Let\'s say I have these two overloads:

void Log(const wchar_t* message)
{
    // Do something
}

void Log(const std::wstring& message)
{
    // Do someth         


        
7条回答
  •  醉话见心
    2020-12-17 20:37

    Adding this alternative for future reference. It comes from the SO question Is it possible to overload a function that can tell a fixed array from a pointer?

    #include 
    #include 
    
    template
    std::enable_if_t::value>
    foo(T)
    {
        std::cout << "pointer\n";
    }
    
    template
    void foo(T(&)[sz])
    {
        std::cout << "array\n";
    }
    
    int main()
    {
      char const* c = nullptr;
      char d[] = "qwerty";
      foo(c);
      foo(d);
      foo("hello");
    }
    

    The above snippet compiles and runs fine on http://webcompiler.cloudapp.net/

提交回复
热议问题