C++ 将变量转换为模板参数

2023-12-19

我想使用模板进行优化,如上所述here https://stackoverflow.com/a/8805655/1341914。但是,随着 bool 模板参数数量的不断增加,实例化模板可能会有太多分支。如果您使用更大的枚举而不是布尔值,它会变得更加分支。

#include <iostream>
using namespace std;

template <bool b1, bool b2>
int HeavyLoop_impl(int arg)
{
    for (int i = 0; i < 10000000; i++)
    {
        // b1 is known at compile-time, so this branch will be eliminated
        if (b1) { arg += 1; }
        else    { arg += 2; }

        // b2 is known at compile-time, so this branch will be eliminated
        if (b2) { arg += 10; }
        else    { arg += 20; }
    }
    return arg;
}

// This function could be generated automatically
void HeavyLoop(bool b1, bool b2, int arg)
{
    int res;
    if (b1) {
        if (b2) { res = HeavyLoop_impl<true, true>(arg); }
        else    { res = HeavyLoop_impl<true, false>(arg); }
    } else {
        if (b2) { res = HeavyLoop_impl<false, true>(arg); }
        else    { res = HeavyLoop_impl<false, false>(arg); }
    }
    cout << "res: "<<res<<endl;
}

int main(int argc, char**argv)
{
    bool b1 = true;
    bool b2 = false;
    int arg = 0;
    HeavyLoop(b1, b2, arg);
    return 0;
}

有没有办法自动生成HeavyLoop函数?我想要这样的东西:

vars_to_template_function<bool, bool>(HeavyLoop_impl, b1, b2, arg);

这有可能吗?感谢您的任何提示。

注意:这只是一个非常简化的示例。实际的循环当然更复杂:o)


我决定从代码中获得更多乐趣,这是我第一次尝试的改进版本,它具有以下优点:

  • 支持enum types
  • 明确指定应转换多少个参数
  • 复杂部分的通用实现,每个使用它的函数都有一个小助手。

代码:

#include <iostream>
#include <utility>
#include <type_traits>

// an enum we would like to support
enum class tribool { FALSE, TRUE, FILE_NOT_FOUND };

// declare basic generic template
// (independent of a specific function you'd like to call)
template< template< class > class CB, std::size_t N, typename = std::tuple<> >
struct var_to_template;

// register types that should be supported
template< template< class > class CB, std::size_t N, typename... Cs >
struct var_to_template< CB, N, std::tuple< Cs... > >
{
    // bool is pretty simple, there are only two values
    template< typename R, typename... Args >
    static R impl( bool b, Args&&... args )
    {
        return b
          ? var_to_template< CB, N-1, std::tuple< Cs..., std::true_type > >::template impl< R >( std::forward< Args >( args )... )
          : var_to_template< CB, N-1, std::tuple< Cs..., std::false_type > >::template impl< R >( std::forward< Args >( args )... );
    }

    // for each enum, you need to register all its values
    template< typename R, typename... Args >
    static R impl( tribool tb, Args&&... args )
    {
        switch( tb ) {
        case tribool::FALSE:
          return var_to_template< CB, N-1, std::tuple< Cs..., std::integral_constant< tribool, tribool::FALSE > > >::template impl< R >( std::forward< Args >( args )... );
        case tribool::TRUE:
          return var_to_template< CB, N-1, std::tuple< Cs..., std::integral_constant< tribool, tribool::TRUE > > >::template impl< R >( std::forward< Args >( args )... );
        case tribool::FILE_NOT_FOUND:
          return var_to_template< CB, N-1, std::tuple< Cs..., std::integral_constant< tribool, tribool::FILE_NOT_FOUND > > >::template impl< R >( std::forward< Args >( args )... );
        }
        throw "unreachable";
    }

    // in theory you could also add int, long, ... but
    // you'd have to switch on every possible value that you want to support!
};

// terminate the recursion
template< template< class > class CB, typename... Cs >
struct var_to_template< CB, 0, std::tuple< Cs... > >
{
    template< typename R, typename... Args >
    static R impl( Args&&... args )
    {
        return CB< std::tuple< Cs... > >::template impl< R >( std::forward< Args >( args )... );
    }
};

// here's your function with the template parameters
template< bool B, tribool TB >
int HeavyLoop_impl( int arg )
{
    for( int i = 0; i < 10000000; i++ ) {
        arg += B ? 1 : 2;
        arg += ( TB == tribool::TRUE ) ? 10 : ( TB == tribool::FALSE ) ? 20 : 30;
    }
    return arg;
}

// a helper class, required once per function that you'd like to forward
template< typename > struct HeavyLoop_callback;
template< typename... Cs >
struct HeavyLoop_callback< std::tuple< Cs... > >
{
    template< typename R, typename... Args >
    static R impl( Args&&... args )
    {
        return HeavyLoop_impl< Cs::value... >( std::forward< Args >( args )... );
    }
};

// and here, everything comes together:
int HeavyLoop( bool b, tribool tb, int arg )
{
    // you provide the helper and the number of arguments
    // that should be converted to var_to_template<>
    // and you provide the return type to impl<>
    return var_to_template< HeavyLoop_callback, 2 >::impl< int >( b, tb, arg );
}

int main()
{
    bool b = true;
    tribool tb = tribool::FALSE;
    int arg = 0;
    int res = HeavyLoop( b, tb, arg );
    std::cout << "res: " << res << std::endl;
    return 0;
}

这是一个活生生的例子 http://coliru.stacked-crooked.com/a/99a48a69df68c7c3如果你想玩它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ 将变量转换为模板参数 的相关文章

  • 将 new 与 decltype 一起使用

    T t T is an implementation detail t new T want to avoid naming T to allow for flexibility t new decltype t error cannot
  • Poco c++Net:Http 从响应中获取标头

    我使用 POCO C Net 库进行 http 我想尝试制定持久缓存策略 首先 我认为我需要从缓存标头中获取过期时间 并与缓存值进行交叉检查 如果我错了 请告诉我 那么我如何从中提取缓存头httpResponse 我已经看到你可以用 Jav
  • 为什么 F# 的默认集合是排序的,而 C# 的不是?

    当从 C 世界迁移到 F 最惯用的可能 思维方式时 我发现了这个有趣的差异 在 C 的 OOP mutable 世界中 默认的集合集合似乎是HashSet https learn microsoft com en us dotnet api
  • 在 omp 并行 for 循环中使用 unique_ptr 会导致 SEG.FAULT

    采取以下代码 include
  • 使用 LINQ 更新 IEnumerable 对象的简单方法

    假设我有一个这样的业务对象 class Employee public string name public int id public string desgination public int grade List
  • 增强精神、递归和堆栈溢出

    为什么下面的代码在运行时崩溃 它会给出堆栈溢出错误 include
  • MFC:如何设置CEdit框的焦点?

    我正在开发我的第一个简单的 MFC 项目 但我正在努力解决一个问题 想要设置所有的焦点CEdit其中一个对话框中的框 我的想法是 当打开对话框时 焦点位于第一个编辑框上 然后使用 选项卡 在它们之间交换 我看到了方法SetFocus 但我无
  • 将接口转换为其具体实现对象,反之亦然?

    在 C 中 当我有一个接口和几个具体实现时 我可以将接口强制转换为具体类型 还是将具体类型强制转换为接口 这种情况下的规则是什么 Java 和 C 中都允许这两个方向 向下转型需要显式转型 如果对象类型不正确 可能会抛出异常 然而 向上转换
  • 如何对 NServiceBus.Configure.WithWeb() 进行单元测试?

    我正在构建一个 WCF 服务 该服务接收外部 IP 上的请求并将其转换为通过 NServiceBus 发送的消息 我的单元测试之一调用Global Application Start 它执行应用程序的配置 然后尝试将 Web 服务解析为 验
  • 析构函数中的异步操作

    尝试在类析构函数中运行异步操作失败 这是代码 public class Executor public static void Main var c1 new Class1 c1 DoSomething public class Class
  • 搜索实体的所有字段

    我正在尝试在客户数据库上实现 多功能框 类型的搜索 其中单个查询应尝试匹配客户的任何属性 这是一些示例数据来说明我想要实现的目标 FirstName LastName PhoneNumber ZipCode Mary Jane 12345
  • 引用/指针失效到底是什么?

    我找不到任何定义指针 引用无效在标准中 我问这个问题是因为我刚刚发现 C 11 禁止字符串的写时复制 COW 据我了解 如果应用了 COW 那么p仍然是一个有效的指针并且r以下命令后的有效参考 std string s abc std st
  • 如何使用 NPOI 按地址(A1、A2)获取 Excel 单元格值

    我有一个 Excel 单元格地址 例如 A1 A2 如何使用 C 中的 NPOI 框架以编程方式访问此单元格 我找到的一些 Java POI 示例代码 CellReference cr new CellReference A1 row my
  • ASP.NET MVC 路由:如何从 URL 中省略“索引”

    我有一个名为 StuffController 的控制器 具有无参数索引操作 我希望从表单中的 URL 调用此操作mysite com stuff 我的控制器定义为 public class StuffController BaseContr
  • 逆向工程 ASP.NET Web 应用程序

    我有一个 ASP NET Web 应用程序 我没有源代码 该 bin 包含 10 个程序集和一个 compiled 文件 我在 App Code dll 上使用 Reflector 它向我显示了类和命名空间之类的东西 但它太混乱了 有没有什
  • 选择查询不适用于使用Parameters.AddWithValue 的参数

    C 中的以下查询不起作用 但我看不出问题所在 string Getquery select from user tbl where emp id emp id and birthdate birthdate cmdR Parameters
  • 如何得知客户端从服务器的下载速度?

    根据客户的下载速度 我想以低质量或高质量显示视频 任何 Javascript 或 C 解决方案都是可以接受的 Thanks 没有任何办法可以确定 您只能测量向客户端发送数据的速度 如果没有来自客户端的任何类型的输入来表明其获取信息的速度 您
  • 来自 3rd 方库的链接器错误 LNK2019

    我正在将旧的 vc 6 0 应用程序移植到 vs2005 我收到以下链接器错误 我花了几天时间试图找到解决方案 错误LNK2019 无法解析的外部符号 imp 创建AwnService 52 在函数 public int thiscall
  • DataContractSerializer 事件/委托字段问题

    在我的 WPF 应用程序中 我正在使用DataContractSerializer序列化对象 我发现它无法序列化具有事件或委托声明的类型 考虑以下失败的代码 Serializable public abstract class BaseCl
  • 如何将 SQL“LIKE”与 LINQ to Entities 结合使用?

    我有一个文本框 允许用户指定搜索字符串 包括通配符 例如 Joh Johnson mit ack on 在使用 LINQ to Entities 之前 我有一个存储过程 该存储过程将该字符串作为参数并执行以下操作 SELECT FROM T

随机推荐

  • C 中的原子读取

    根据C 对 int 的读写是原子的吗 https stackoverflow com questions 54188 are c reads and writes of an int atomic 由于处理器缓存的问题 整数的读取 因此指针
  • 为什么 Python 脚本可以在 CLI 中运行,但在 cron 作业调用时却不能运行?

    我创建了一个 Python 脚本 我想通过 Ubuntu 服务器上的 cronjob 每天运行它 这是从命令行运行该脚本的方式 python home username public html IDM app manage py clean
  • 增强多索引容器的模板参数

    我需要创建一个包含多索引容器作为存储的通用类 当我编译时 它给出如下错误 其中我定义了第 n 个索引视图 错误 非模板 nth index 用作模板 connection manager 模板 类 conn mgr boost noncop
  • 实体框架从 6.1.x 升级到 6.2.0 会破坏某些查询,除非我启用 MARS

    我最近在我们的一个大型项目中将 EF 6 1 3 升级到 6 2 0 它破坏了我们大量的 LINQ 查询 启用 MultipleActiveResultSets 会使一切再次正常工作 但我很难理解这种变化 我们已经使用 EF 多年 并且经历
  • Three.js 中的剪辑是自动完成的吗?

    所以 我正在阅读有关剪辑的内容this http en wikipedia org wiki Clipping 28computer graphics 29维基百科文章 这似乎对所有游戏都非常重要 所以 我是否必须这样做 还是由 Three
  • GDB:在每一步后禁用当前行的打印

    GNU gdb 命令行调试器在每次执行后打印当前所在的行step and next命令 考虑以下 gdb 会话 我在其中单步执行一些代码 Temporary breakpoint 1 main argc 1 argv 0x7fffffffd
  • 如何在 Haskell 中将小数解析为有理数?

    我一直在参加编程竞赛 http codeforces com contest 105 and 问题之一 http codeforces com contest 105 problem A 输入数据包括十进制格式的小数 0 75就是一个例子
  • PDFkit Rails3.1和开发环境

    我的 Rails 3 1 应用程序正在使用 PDFkit 来渲染特定页面 并且我遇到了 看起来像是 一个常见问题 尝试生成 pdf 导致进程挂起 我在 stackoverflow 上找到了这个解决方案 Rails 3 和 PDFkit ht
  • 如何在 jQuery 的 SELECT 元素中选择特定选项?

    如果您知道索引 值或文本 如果您没有可直接参考的 ID 也同样如此 This https stackoverflow com questions 149573 check if option is selected with jquery
  • asp.net mvc4 jquery 不工作

    我正在尝试运行放入我的 jquery 代码 布局 cshtml如下 Scripts Render bundles jquery RenderSection Scripts required false 上面的代码没有被触发 当我用 Chro
  • Dart 初始化最终变量

    我在dart中编写构造函数时遇到了问题 我有一个类有两个final变量 在构造函数中初始化它们 以下是错误的 因为final变量没有setter方法 class Person final String name final int age
  • 鼠标右键映射为用于在 Jelly Bean 中向后移动

    我们更改了 framework base services input inputreader cpp 中的部分代码 使鼠标右键可以向后遍历 case BTN RIGHT mBtnRight rawEvent gt value break
  • PHP 和 Laravel 的特征

    我正在使用 Laravel 5 1 当模型之前的模型使用appends array 如果我的特征中存在某些项目 我想将其添加到附加数组中 我不想编辑模型来实现这一目标 在这种情况下 特征实际上可用吗 或者我应该使用继承 array push
  • Laravel 4:如何将 WHERE 条件应用于 Eloquent 类的所有查询?

    我正在尝试为我拥有的表实现 已批准 状态 这非常简单 基本上 如果该行的批准列等于 1 则应该检索该行 否则不应检索 问题是 现在我必须遍历整个代码库并添加 WHERE 语句 即函数调用 这不仅耗时而且效率低下 如果我想删除该功能等 我怎样
  • 如何在 DynamoDB 中实现按项目的任意属性排序

    我的 DynamoDB 结构如下 我有患者 其患者信息存储在其文档中 我有索赔 索赔信息存储在其文档中 我的付款信息存储在其文档中 每项索赔都属于患者 患者可以提出一项或多项索赔 每一笔付款都属于患者 患者可以有一次或多次付款 I crea
  • 为什么马赛克::衍生因子比基函数慢两倍?

    我正在尝试使用derivedFactor来自mosaic在 R 中打包来创建因子变量 但速度慢得惊人 当我使用一系列代码编写相同的函数时if声明并运行 它的运行速度似乎几乎快了一倍 这是一个可重现的示例 抱歉长度太长 library mic
  • 在 Firestore 中查询 GeoHashes 不会返回任何内容

    Firebase 网站上给出了从 Firestore 检索给定点 50 公里位置内所有位置的代码 这里是 Find cities within 50km of London let center CLLocationCoordinate2D
  • 在 IE 8/9 中使用“use strict”是否安全

    根据这个http caniuse com use strict http caniuse com use strict use strict IE 8 9 版本不支持 我的问题是 在 IE 8 9 或不兼容的浏览器中使用 use stric
  • 如何获得逻辑回归特征对于特定预测的相对重要性?

    我正在使用逻辑回归 在 scikit 中 来解决二元分类问题 并且有兴趣能够解释每个单独的预测 更准确地说 我感兴趣的是预测正类的概率 并衡量每个特征对于该预测的重要性 使用系数 Beta 作为重要性衡量标准通常是一个坏主意正如这里所回答的
  • C++ 将变量转换为模板参数

    我想使用模板进行优化 如上所述here https stackoverflow com a 8805655 1341914 但是 随着 bool 模板参数数量的不断增加 实例化模板可能会有太多分支 如果您使用更大的枚举而不是布尔值 它会变得