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

后端 未结 4 829
再見小時候
再見小時候 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:43

    Suppose you want to pass the argument pointer of type void* (or simply nullptr) to your processPointer function and you also want to call its specialization for type Type. Then you should write

    processPointer(static_cast(pointer));
    

    for

    void processPointer(void*) = delete;
    

    But for

    template<>
    void processPointer(void*) = delete;
    

    you could write the code which is much shorter:

    processPointer(pointer);
    

    So both variants can be used in the different cases.

    However the analogue of the variant with non-template overload can be the only way in some cases. Suppose there is a function template with two parameters:

    template
    void processPointer(T* ptr1, U* ptr2);
    

    You don't want it to be called with void* pointers as the first argument. The partial specialization of function templates is not allowed in C++ so this code is incorrect:

    template
    void processPointer(void*, U*) = delete;
    

    And you must use another one:

    template
    void processPointer(void*, U*) = delete;
    

提交回复
热议问题