我何时会在constexpr上使用std :: integral_constant?

Tre*_*key 40 c++ templates constants constexpr c++11

#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';

}
Run Code Online (Sandbox Code Playgroud)

有关std :: integral_constant的特别之处,我会选择在constexpr上使用它吗?
他们的行为和用例看起来与我相同.我正在尝试考虑某种模板场景,其中constexpr可能不够.

For*_*veR 35

模板integral_constant定义一个类型,关键字constexpr定义一个常量.例如std::true_typestd::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());
}
Run Code Online (Sandbox Code Playgroud)

实例

  • @TrevorHickey它不会有另一种类型,在constexpr的情况下它只会有类型bool. (3认同)
  • 不是一般情况.编译器(至少gcc)将尝试在所有"可到达"块中实例化对象,即使优化器由于constexpr条件将要稍后剔除这些块.模板化表达式不会发生这种情况,因为事先会发生SFINAE推理. (3认同)

Que*_*nUK 6

它可以与三元运算符一起使用,例如

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
}
Run Code Online (Sandbox Code Playgroud)