如何确定函数的返回值在编译时选择可能的选项
How to determine a functions` return value choosing possible options at compile time
我有两个几乎相同的函数,它们接收与参数相同的结构。我的功能的非常简化的版本如下:
struct Container {
int A;
int B;
}
int return_A_dependent(Container c){
//... identical code for A and B ...
int common_for_A_and_B = 0;
return common_for_A_and_B + c.A;
}
int return_B_dependent(Container c){
// ... identical code for A and B ...
int common_for_A_and_B = 0;
return common_for_A_and_B + c.B;
}
两个函数之间只有差异是其返回值取决于结构的不同变量。我想在不进行运行时检查的情况下组合这两个功能。就像传递标志参数并添加一个if语句以转发返回值如下:
int return_A_or_B(Container c, bool flag_A) {
// ... identical code for A and B ...
int common_for_A_and_B = 0;
if (flag_A) {
return common_for_A_and_B + c.A;
}
else {
return common_for_A_and_B + c.B;
}
如何在不使用"如果"的情况下在编译时处理此操作?预先感谢。
使用指针作为参数的指针(或仅具有额外参数的正常函数):
template<int Container::* p_member> int
Work(Container c)
{
int common_for_A_and_B = 0;
return common_for_A_and_B + c.*p_member;
}
Work<&Container::A>(c);
相关文章:
- 两个函数模板候选项.将一个参数作为引用后,选择不太专业的模板
- 如何在 DirectX 11 应用程序中提供选择图形适配器的选项?
- 我如何在Qt中选择构建选项
- 如何防止在 switch 语句中多次选择同一选项/值
- 是/否总是选择第一个选项(C )
- 如何确定函数的返回值在编译时选择可能的选项
- 如何防止用户多次选择一个选项
- 在菜单前键入字符串后,C 如何从菜单中选择选项
- 如何在选择错误选项时保持程序运行而不退出
- 正在更新选项卡选择的CPropertyPage
- 选择哪个选项在C++中使用sql
- IFstream在选择菜单选项后无法打开文件
- Scons 选择哪个版本的 g++ |无法识别的命令行选项"-std=c++11"
- 在双括号 QString 之间仅选择一个选项
- 在提升构建中根据操作系统选择编译器选项
- 当选择一个选项时,如何执行另一个c++程序
- C 使用 Y/N 选项循环开关。选择 N 不会关闭程序
- 根据第一个选项选择选项组
- 仅为QFileSystemModel的第一列(驱动器、文件夹、文件)选择选项
- 如何禁用CListCtrl选择选项