Conditionally provide a using declaration

Viewed 116

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?

2 Answers

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>
{};

If you want don't want your program to compile with foo<void> and don't mind ugly SFINAE, then here is an ugly solution with no specialization:

template< typename T, typename = std::enable_if_t<!std::is_same_v<void, T>>>
struct foo
{
    using reference = T&;
    using const_reference = T const&;
};
Related