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

 九天0307_963 发布于 2023-02-13 05:22

模板integral_constant定义一个类型,关键字constexpr定义一个常量.例如std::true_typestd::integral_constant.

其中一个用法示例是tag-dispatching.

template
void use_impl(const T&, std::false_type)
{
}

template
void use_impl(const T&, std::true_type)
{
}

template
void use(const T& v)
{
   use_impl(v, typename std::is_integral::type());
}

实例

2 个回答
  • 它可以与三元运算符一起使用,例如

    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
    }
    

    2023-02-13 05:50 回答
  • 模板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());
    }
    

    实例

    2023-02-13 05:55 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有