Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

negation of std::integral_constant<bool>

Sorry for asking so simple question, but I cannot find the answer easily. Google says nothing interesting about "C++ negation integral_constant" and similar queries.

Is there in C++11 any trait that make std::true_type from std::false_type and vice versa? In other words, I'd like some more readeble version of

std::is_same<my_static_bool, std::false_type>

I know of course I can write it myself, but I'd like to use the existing one if there is such.

like image 760
peper0 Avatar asked Feb 06 '13 20:02

peper0


3 Answers

There is not, because it's essentially a one-liner and the <type_traits> should be as small as possible.

template <typename T> using static_not = std::integral_constant<bool, !T::value>;

Usage:

static_not<my_static_bool>

This is the correct way because the standard always says "false_type or derived from such", so you can't depend on being equal to std::false_type. I usually relax that to "having a constexpr boolean ::value property" because I don't use tag dispatching.

like image 184
ipc Avatar answered Nov 04 '22 09:11

ipc


Yet another way to do it:

template <typename T>
using static_not = typename std::conditional<
    T::value,
    std::false_type,
    std::true_type
>::type;
like image 36
aschepler Avatar answered Nov 04 '22 09:11

aschepler


The following code uses template metafunction forwarding (i.e. it inherits from std::integral_constant with a negated boolean value, this is of course inspired by the Boost.MPL that heavily uses this pattern)

#include <type_traits>

template<typename T>
struct logical_not
:
    std::integral_constant<bool, !T::value>
{};

int main()
{
   typedef logical_not<std::false_type>::type T;
   typedef logical_not<std::true_type>::type F;

   static_assert((std::is_same<T, std::true_type>::value), "");
   static_assert((std::is_same<F, std::false_type>::value), "");   
}

Output on LiveWorkSpace

like image 2
TemplateRex Avatar answered Nov 04 '22 11:11

TemplateRex