Is it possible to overload a function that can tell a fixed array from a pointer?

前端 未结 6 1832
感动是毒
感动是毒 2020-12-05 14:06

Motivation:

Almost for fun, I am trying to write a function overload that can tell apart whether the argument is a fixed-size array or a pointer.

6条回答
  •  抹茶落季
    2020-12-05 14:45

    This seems to work for me

    #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;
      foo(c);
      foo("hello");
    }
    

    Bonus std::experimental::type_traits:

    using std::experimental::is_pointer_v;
    std::enable_if_t>
    

    Your comment made me try something even simpler

    template void foo(T) { std::cout << "pointer\n"; }
    template void foo(T(&)[sz]) { std::cout << "array\n"; }
    

    Of course the problem here is that foo is now callable for any type, depends on how lax you want your parameter checking to be.


    One other way is to (ab)use rvalue references

    void foo(char const*&) { std::cout << "pointer\n"; }
    void foo(char const*&&) { std::cout << "array\n"; }
    

    Obviously it's not foolproof.

提交回复
热议问题