In function call, why doesn't nullptr match a pointer to a template object?

后端 未结 5 1943
萌比男神i
萌比男神i 2021-02-20 11:29

Here is an example of a code that works perfectly:


#include
#include

template< class D, template< class D, class A >         


        
5条回答
  •  被撕碎了的回忆
    2021-02-20 12:25

    This is just how template deduction work: no conversion take place.

    The problem is not endemic to nullptr either, consider the extremely simple case:

    #include 
    
    struct Thing {
        operator int() const { return 0; }
    } thingy;
    
    template 
    void print(T l, T r) { std::cout << l << " " << r << "\n"; }
    
    int main() {
        int i = 0;
        print(i, thingy);
        return 0;
    }
    

    which yields:

    prog.cpp: In function ‘int main()’:
    prog.cpp:12:17: error: no matching function for call to ‘print(int&, Thing&)’
      print(i, thingy);
                     ^
    prog.cpp:12:17: note: candidate is:
    prog.cpp:8:6: note: template void print(T, T)
     void print(T l, T r) { std::cout << l << " " << r << "\n"; }
          ^
    prog.cpp:8:6: note:   template argument deduction/substitution failed:
    prog.cpp:12:17: note:   deduced conflicting types for parameter ‘T’ (‘int’ and ‘Thing’)
      print(i, thingy);
                     ^
    

    Thus, the conversion of nullptr to int* does not occur prior to template argument deduction either. As mentioned, you have two ways of solving the issue:

    • specifying the template parameters (thus no deduction occur)
    • converting the argument yourself (deduction occurs, but after your explicit conversion)

提交回复
热议问题