When would I use std::integral_constant over constexpr?

C++TemplatesC++11ConstantsConstexpr

C++ Problem Overview


#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.

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

It can be used with the ternary operator eg

void gotoN_impl(std::integral_constant<int,0>::type)
{
	std::cout << "GoTo 0" << '\n';
}

void gotoN_impl(std::integral_constant<int,1>::type)
{
	std::cout << "GoTo 1" << '\n';
}

void gotoN_impl(std::integral_constant<int,2>::type)
{
	std::cout << "GoTo 2" << '\n';
}
 
void gotoN_impl(std::integral_constant<int,3>::type)
{
	std::cout << "GoTo 3" << '\n';
} 

template<int N>
void gotoN()
{
	gotoN_impl(typename std::integral_constant<int, N>::type());
}


int main()
{
	gotoN<0>();
	gotoN<1>();
	gotoN<2>();
	gotoN<3>();
	
	constexpr auto x = 99;
	
	gotoN<x<4?x:3>(); // with a ternary operator
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTrevor HickeyView Question on Stackoverflow
Solution 1 - C++ForEveRView Answer on Stackoverflow
Solution 2 - C++QuentinUKView Answer on Stackoverflow