Askaga
Askaga

Reputation: 6331

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?

Upvotes: 4

Views: 549

Answers (3)

Jarod42
Jarod42

Reputation: 217275

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

Upvotes: 5

HolyBlackCat
HolyBlackCat

Reputation: 96246

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

Upvotes: 4

songyuanyao
songyuanyao

Reputation: 172924

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

Upvotes: 2

Related Questions