Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do static_assert on every other type in a template

How can I do static_asserts (or other checks) on every other type in a template?

template<typename... Ts> //T1,T2,T3,...
struct foo {
  //How can I
  //for T1,T3,T5,T7,...
  //do some checks, for example:
  //static_assert(std::is_default_constructible<Tn>::value,"invalid type");
  //static_assert(std::is_copy_constructible<Tn>::value,"invalid type");
};
like image 905
roger.james Avatar asked Feb 16 '23 02:02

roger.james


1 Answers

Please try this:

#include <type_traits>

template <typename... Ts>
struct default_constructible;

template <typename T>
struct default_constructible<T>
{
    static constexpr bool value = std::is_default_constructible<T>::value;
};

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

template <typename T, typename U, typename... Ts>
struct default_constructible<T, U, Ts...>
{
    static constexpr bool value = std::is_default_constructible<T>::value && default_constructible<Ts...>::value;
};

template <typename... Ts>
struct foo
{
    static_assert(default_constructible<Ts...>::value, "");
};

class A { A() = delete; };

template class foo<int, bool>;      // Compiles
template class foo<int, bool, A>; // Does not compile

Demo

like image 187
David G Avatar answered Feb 28 '23 17:02

David G