P
P
Pinkman2022-03-13 12:20:42
C++ / C#
Pinkman, 2022-03-13 12:20:42

How to allow certain types in a template?

Hello! The question is, how to allow, for example, the types int and double in the template, and put asserts on the rest?

template <class T>
struct Test {
    T workingOnlyWithIntegerOrDouble();
private:
    T num_;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cunion, 2022-03-21
@0hquazEd

template <class T>
struct is_permitted 
{
  static constexpr bool value = false;
};

template <>
struct is_permitted<int>
{
  static constexpr bool value = true;
};

template <>
struct is_permitted<double>
{
  static constexpr bool value = true;
};

template <class T>
struct test
{
  test()
  {
    static_assert(is_permitted<T>::value);
  }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question