简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM