Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 301
Askaga Avatar asked Oct 29 '25 18:10

Askaga


1 Answers

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;
};
like image 89
Jarod42 Avatar answered Oct 31 '25 07:10

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!