Search code examples
c++c++-concepts

How to ensure template parameter is non-const and non-reference


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?


Solution

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