Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between std::conditional and std::conditional_t c++

I cannot find in c++ the difference between std::conditional< >::type and std::conditional_t< > .

When I compile

 using A = typename conditional< true, int, char>::type;                     
 using B = typename conditional_t< true, int, char>::type;     

an error: expected nested-name-specifier gets out. I was unable to use conditional and nest, while conditional_t seems to nest.

like image 579
George Kourtis Avatar asked Sep 11 '26 20:09

George Kourtis


2 Answers

Due to a design flaw in C++ templates, it turns out that creating a helper alias for type-functions is useful.

So std::conditional<bool, A, B> is a type-function template. Its ::type is either A or B.

std::conditional_t<bool, A, B> is an helper alias that evaluates to std::conditional<bool, A, B>::type. In most contexts, doing ::type on std::conditional requires you disambiguate with a typename prefix so the compiler knows that ::type is a type and not a value - but std::conditional_t does this for you, as it is syntactically known to be a type without a typename.

In the C++ std library, almost all (and maybe all) templates with a ::type member now come with a helper _t template that does this, which makes a bunch of use nicer.

like image 182
Yakk - Adam Nevraumont Avatar answered Sep 14 '26 09:09

Yakk - Adam Nevraumont


std::conditional_t is just a helper alias. From cppreference:

template< bool B, class T, class F >
using conditional_t = typename conditional<B,T,F>::type;

On the same link you can also find the statement:

The behavior of a program that adds specializations for std::conditional is undefined.

The same is not true for type traits you write or that come with libraries. And then the crux is that the fact that some_trait::type is a type is only a convention. Nothing in the language forbids you to specialize some_trait such that type is a static member of type int whose value is 42.

And thats why you need to disambiguate the member alias type via typename (see When is the "typename" keyword necessary?). std::conditional_t on the other hand is a type alias. It can only be a type. Its a helper that makes the use of the trait more convenient.

std::conditional_t (usually) has no member alias type. It is an alias for the member alias type of std::conditional.

like image 26
463035818_is_not_a_number Avatar answered Sep 14 '26 09:09

463035818_is_not_a_number



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!