加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 借助模板避免函数重载

发布时间:2020-12-16 10:14:34 所属栏目:百科 来源:网络整理
导读:我有以下重载函数: float myFunc(Vector2D vec) { Temp2D temp; for (int i = 0; i 10; i++) { temp += computeTemp(vec,i); } return temp.compute_a_float(); }float myFunc(Vector3D vec) { Temp3D temp; for (int i = 0; i 10; i++) { temp += computeT
我有以下重载函数:

float myFunc(Vector2D vec) {
  Temp2D temp;
  for (int i = 0; i < 10; i++) {
    temp += computeTemp(vec,i);
  }
  return temp.compute_a_float();   
}

float myFunc(Vector3D vec)  {
  Temp3D temp;
  for (int i = 0; i < 10; i++) {
    temp += computeTemp(vec,i);
  }
  return temp.compute_a_float();
}

float myFunc(Vector4D vec)  {
  Temp4D temp;
  for (int i = 0; i < 10; i++) {
    temp += computeTemp(vec,i);
  }
  return temp.compute_a_float();
}

其中computeTemp也为Vector2D,Vector3D,Vector4D重载:

Temp2D computeTemp(Vector2D,int);
Temp3D computeTemp(Vector3D,int);
Temp4D computeTemp(Vector4D,int);

为了避免代码重复,我提出了添加一个抽象层的想法:

template<typename T0,typename T1>
float myFunc(T0 vec) {
  T1 temp;
  for (int i = 0; i < 10; i++) {
    temp += computeTemp(vec,i);
  }
  return temp.compute_a_float();   
}

float myFunc(Vector2D vec) {
  return myFunc<Vector2D,Temp2D>(vec);
}
float myFunc(Vector3D vec)  {
  return myFunc<Vector3D,Temp3D>(vec);
}
float myFunc(Vector4D vec)  {
  return myFunc<Vector4D,Temp4D>(vec);
}

但是,我想知道是否可以避免额外的抽象层,并直接决定myFunc中变量temp的类型.

解决方法

directly decide the type of variable temp in myFunc.

您可以使用decltype来确定类型,例如

template<typename T0>
float myFunc(T0 vec) {
  decltype(computeTemp(vec,0)) temp;
  for (int i = 0; i < 10; i++) {
    temp += computeTemp(vec,i);
  }
  return temp.compute_a_float();   
}

顺便说一句,

1.请注意,如果computeTemp通过引用返回而不是按值返回,则decltype的结果类型也将是引用(对于lvalue或rvalue,取决于computeTemp返回的方式);你可能需要使用带有decltype的std::remove_reference来获得你想要的类型.

2.用于decltype的表达式属于unevaluated expressions:

The operands of the four operators typeid,sizeof,noexcept,and decltype (since C++11) are expressions that are not evaluated (unless they are polymorphic glvalues and are the operands of typeid),since these operators only query the compile-time properties of their operands. Thus,std::size_t n = sizeof(std::cout << 42); does not perform console output.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读