c++ - 数据类型为 : float, float4、float8、double、double4、int、int4、int8 的模板

标签 c++ templates

我定义了以下数据类型:float、float4、float8、double、double4、int、int4、int8、long(64 位 int)和 long4。假设我定义了以下函数:

void foo_float() {
  float f;
  int i;
  ...do something with f and i
}

void foo_float4() {
  float4 f;
  int4 i;
  ...do something with f and i
}

void foo_double4() {
  double4 f;
  int4 i;
  ...do something with f and i
}

“用 f 和 i 做某事”的部分是相同的。所以我不想写重复的代码。我想改为做类似的事情:

<float, 4>foo()

这会生成函数:

void foo() {
    float4 f;
    int4 i;
    ...do something with f and i
}

有什么建议吗?我可以使用模板执行此操作吗?或者可能是定义语句和模板的组合?

最佳答案

是的,您可以将这组函数变成一个模板函数:

template<typename float_type, typename int_type>
void foo() {
  float_type f;
  int_type i;
  ...do something with f and i
}

然后像这样使用它:

foo<float4, int4>();

关于c++ - 数据类型为 : float, float4、float8、double、double4、int、int4、int8 的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15597645/

相关文章:

c++ - 不一致的 clock_gettime 性能

c++ - Opencv 3.0 与哪个版本的 FFMPEG?

c++ - 为什么 C++ Builder 找不到我的 header ?

string - 如何在 Kotlin 字符串模板中嵌入 for 循环

c++ - 模板 C++0x lambda 函数……还是仿函数/谓词?

c++ - 拆分参数包

c++ - 引用模板类型推导

c++ - 在 C++ 中组织涉及具有有限范围和模板的 const 引用的代码的好方法

c++ - Windows 10 上的 CMake + MinGW + Clang

c++ - 在另一个结构中释放一个结构内的指针