When is deleting a template instantiation preferable to deleting a non-template overload?

后端 未结 4 834
再見小時候
再見小時候 2021-02-05 06:04

Suppose I have a template that works with raw pointers:

template
void processPointer(T* ptr);

I don\'t want this to be called

4条回答
  •  长情又很酷
    2021-02-05 06:34

    This might give insight:

    #include 
    
    struct X
    {
        template
        void processPointer(T* ptr) {
            std::cout << "Template\n";
        }
    
        // error: explicit specialization in non-namespace scope ‘struct X’
        // template<>
        // void processPointer(void*) = delete;
    
        // Overload but no specialization
        // This will prevent lookup the specialization outside the class, when no
        // template argument is explicitly given.  However, with an explicit 
        // template argument the specialization is called.
        void processPointer(void*) = delete;
    };
    
    // Specialization outside the class body
    template<>
    void X::processPointer(void* ptr) {
        std::cout << "Specialization\n";
    }
    
    int main ()
    {
        X x;
        //error: use of deleted function ‘void X::processPointer(void*)’
        //x.processPointer((void*)0);
    
        // Explicit template argument:
        x.processPointer((void*)0);
    }
    

    Conclusion: The answer of @Casey holds.

提交回复
热议问题