Bernard
Bernard

Reputation: 5666

Compile-time boolean operations for an integral_constant?

In the C++ standard library, are there template types that are boolean operations on integral_constant<bool, X> (where X is either true or false)?

As a simple example, you have two overloads of a function as such:

void foo_impl(false_type){
    cout << "false" <<endl;
}

void foo_impl(true_type){
    cout << "true" <<endl;
}

One of these functions is chosen by another function, based on a constant condition:

struct first_tag{};
struct second_tag{};
struct third_tag{};

template <typename TTag>
void foo(TTag role){
    foo_impl(typename constant_or<typename is_same<role, first_tag>::type, typename is_same<role, second_tag>::type>::type{});
}

In this case, the true version of foo_impl() is to be be called if the parameter to foo() is of type first_tag or second_tag, hence the use of a hypothetical type constant_or.

While it is simple to write my own version of constant_or, does such a type already exist in the C++ standard library?

Upvotes: 0

Views: 710

Answers (2)

Passer By
Passer By

Reputation: 21131

First lets fix your typo

template <typename TTag>
void foo(TTag){
    foo_impl(typename constant_or<typename is_same<TTag, first_tag>::type, typename is_same<TTag, second_tag>::type>::type{});
}

is_same acts on types not values.

Then lets point out you can just use the value in is_same.

template <typename TTag>
void foo(TTag){
    foo_impl(integral_constant<bool, is_same_v<TTag, first_tag> | is_same_v<TTag, second_tag>>{});
}

And you're done. Saves a lot of typing too, which is always a plus.

On the note of saving typing (because god forbid)

template<bool B>
using bool_constant = integral_constant<bool, B>;

is defined by the standard.

Upvotes: 2

erenon
erenon

Reputation: 19118

It is called std::conditional. Similar metafunctions, conjunction, disjunction, negation are also coming in C++17.

Upvotes: 1

Related Questions