本文介绍了什么时候在constexpr上使用std :: integral_constant?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#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';
}
std有什么特别之处::我会选择在
他们的行为和用例与我相同。我正在尝试考虑某种模板方案,其中constexpr可能不够用。 constexpr
?
上使用我的积分_constant
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.
推荐答案
模板 integral_constant
定义类型,关键字 constexpr
定义一个常量。
例如 std :: true_type
是 std :: integral_constant< bool,true>
。
Template integral_constant
defines a type, keyword constexpr
defines a constant.For example std::true_type
is std::integral_constant<bool, true>
.
使用示例之一是标记分发
。
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());
}
这篇关于什么时候在constexpr上使用std :: integral_constant?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!