[英]How to determine a functions` return value choosing possible options at compile time
I have two virtually identical function that receive same struct as parameter.我有两个几乎相同的函数,它们接收相同的结构作为参数。 A very simplified version of my functions like below:
我的函数的一个非常简化的版本,如下所示:
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;
}
only difference between two functions is their return values that are depend on the structs' different variables.两个函数之间的唯一区别是它们的返回值取决于结构的不同变量。 I want to combine these two functions without doing runtime check.
我想在不进行运行时检查的情况下组合这两个函数。 Like passing a flag parameter and add a if statement to forward the return value like below:
就像传递一个标志参数并添加一个 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;
}
How could I handle this at compile time without using "if"?我如何在不使用“if”的情况下在编译时处理这个问题? Thanks in advance.
提前致谢。
template using pointer to member as a parameter (or just normal function with extra argument):使用指向成员的指针作为参数的模板(或只是带有额外参数的普通函数):
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.