Home > Blockchain >  How to ensure template parameter is non-const and non-reference
How to ensure template parameter is non-const and non-reference

Time:10-30

Often (most of the time?) when creating types with template type parameters you want to ensure the type parameter is filled in with a non-reference, unqualified (non-const, non-volatile) type. However, a simple definition like the following lets the user fill in any type for T:

template <typename T>
class MyContainer {
    T* whatever;
    T moreStuff;
};

Modern C has concepts that should be able to take care of this problem. What is the best (and preferably least boilerplate-y) way to do this?

CodePudding user response:

static_assert is a good option:

#include <type_traits>

template <typename T>
class MyContainer
{
    static_assert(!std::is_reference_v<T>);
    static_assert(!std::is_const_v<T>);
    static_assert(!std::is_volatile_v<T>);

    T* whatever;
    T moreStuff;
};

CodePudding user response:

I'd use a concept for this.

template <typename T>
concept cvref_unqualified = std::is_same_v<std::remove_cvref_t<T>, T>;
template <cvref_unqualified T>
class MyContainer {...};

CodePudding user response:

You can check the type via static_assert like

template <typename T>
class MyContainer {
    static_assert(std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, T>, "T must be non-reference, unqualified type");
    T* whatever;
    T moreStuff;
};
  • Related