#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::integral_constant
有什么特别之处,我会选择使用它而不是 constexpr
?
他们的行为和用例看起来和我一模一样。我正在尝试考虑某种模板场景,其中 constexpr 可能不够。
最佳答案
模板 integral_constant
定义一个类型,关键字constexpr
定义一个常数。
例如 std::true_type
是 std::integral_constant<bool, true>
.
其中一个用法示例是 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());
}
关于c++ - 我什么时候会在 constexpr 上使用 std::integral_constant?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20368187/