c++ - 我什么时候会在 constexpr 上使用 std::integral_constant?

标签 c++ templates c++11 constants 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';

}

std::integral_constant 有什么特别之处,我会选择使用它而不是 constexpr
他们的行为和用例看起来和我一模一样。我正在尝试考虑某种模板场景,其中 constexpr 可能不够。

最佳答案

模板 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());
}

Live example

关于c++ - 我什么时候会在 constexpr 上使用 std::integral_constant?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20368187/

相关文章:

c++ - Boost 链接错误 undefined reference to GLIBCXX_3.4

C++:将对象传递给函数

c++ - 如何声明同一类的成员 vector ?

c++ - unique_ptrs 的循环 vector 并为运行时类型调用正确的重载

C++11构造函数和析构函数顺序

c++ - std::future 作为函数 C++ 的参数

c++ - 使用 wcstod 转换零值

c++ - 从函数指针静态推断标准 C++98 中的函数类型参数

c++ - Dev C++ 控制台窗口属性

c++ - 如何在不更改类模板的情况下为模板类的模板方法添加第二种类型?