Why is a C++ template accepting an array not more specialized than one accepting a pointer according to GCC 5.3 and Clang 4.0?

后端 未结 1 1343
无人及你
无人及你 2021-02-05 12:32

Why are the next two template declarations ambiguous (so neither is more specialized than the other)? I know this question has been raised many times on Stack Overflow, but usua

相关标签:
1条回答
  • 2021-02-05 13:05

    The template declarations are not ambiguous; the following code compiles and runs OK:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    template<class T>
    void func(char* buf, T size) {cout<<"void func(char*,T)\n";}
    template<size_t N>
    void func(char (&buf)[N], std::size_t size) {
      cout<<"void func(char (&)[],size_t)\n";}
    
    int main() {
      char buf[3];
      func(buf, 2);
      func<3>(buf, 2);
      func(reinterpret_cast<char (&)[3]>(buf), 2);
      //next is ambiguous
      //func(reinterpret_cast<char (&)[3]>(buf), size_t(2));
      func<3>(reinterpret_cast<char (&)[3]>(buf), size_t(2));
      return 0;
    }
    

    However, the commented-out call is ambiguous. To disambiguate it use:

    func<3>(reinterpret_cast<char (&)[3]>(buf), size_t(2));
    

    This works OK and calls the correct function.

    0 讨论(0)
提交回复
热议问题