Template func and non template func call order

后端 未结 2 766
予麋鹿
予麋鹿 2021-01-15 03:02

In Linux I get

template max() is called

But under Windows I get

non-template max() is called

Why? In Li

2条回答
  •  走了就别回头了
    2021-01-15 03:50

    The call of max in Imax depend on T and thus max should be searched in the template definition context (where the template max is) and combined with the argument dependent lookup in the instantiation context. ADL shouldn't find the free standing max as int have no associated namespace. So my take is that gcc is correct.

    Note that if you have the slight variation:

    #include 
    #include 
    
    struct S {};
    
    template < typename T > 
    inline void max( const S& a, const T& b ) 
    {
        std::cout << "template max() is called" << std::endl;
    }
    
    template < typename T > 
    inline void Imax( const S& a, const std::vector& b)
    {
        max(a, b[0]);
    }
    
    inline void max( const S& a, const S& b ) 
    {
        std::cout << "non-template max() is called" << std::endl;
    }
    
    int main()
    {
        std::vector v;
        v.push_back(S());
        Imax(S(), v);       
        return 0;
    }
    

    here, the global namespace is associated with S, and thus the non template max is found by the ADL lookup at the point of instantiation.

提交回复
热议问题