Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would I use std::integral_constant over constexpr?

#include <iostream> #include <type_traits>  int main(){      //creating an integral constant with constexpr     constexpr unsigned int speed_of_light{299792458};      //creating an integral constant with std::integral_constant     typedef std::integral_constant<unsigned int, 299792458> speed_of_light_2;      //using them     std::cout << speed_of_light/2 << '\n';     std::cout << speed_of_light_2::value/2 << '\n';  } 

What's special about std::integral_constant that I would choose to use it over constexpr?
Their behaviour and use cases look identical to me. I'm trying to think of some kind of template scenario, where constexpr may not suffice.

like image 297
Trevor Hickey Avatar asked Dec 04 '13 06:12

Trevor Hickey


People also ask

What is the use of Integral_constant?

std::integral_constant This template is designed to provide compile-time constants as types. It is used by several parts of the standard library as the base class for trait types, especially in their bool variant: see true_type and false_type. Its definition in the Standard Library has the same behavior as: C++11.

What is STD Integral_constant?

std::integral_constant wraps a static constant of specified type. It is the base class for the C++ type traits. The behavior of a program that adds specializations for integral_constant is undefined.


1 Answers

Template integral_constant defines a type, keyword constexpr defines a constant. For example std::true_type is std::integral_constant<bool, true>.

One of the usage examples is tag-dispatching.

template<typename T> void use_impl(const T&, std::false_type) { }  template<typename T> void use_impl(const T&, std::true_type) { }  template<typename T> void use(const T& v) {    use_impl(v, typename std::is_integral<T>::type()); } 

Live example

like image 57
ForEveR Avatar answered Sep 30 '22 04:09

ForEveR