Search code examples
c++templatesc++17type-traitsenable-if

Conditionally provide a using declaration


Suppose I've got a class foo with template parameter T and I want to provide a using declaration for the reference and const-reference types corresponding to T:

template<typename T>
struct foo
{
    using reference = T&;
    using const_reference = T const&;
};

Is there a way to "enable" these using declerations only if T is not void without speclializing the whole class foo?


Solution

  • You could inherit from a base class with a specialization for void:

    template<typename T>
    struct typedefs {
        using reference = T&;
        using const_reference = T const&;
    };
    
    template<>
    struct typedefs<void> {};
    
    template<typename T>
    struct foo : typedefs<T>
    {};