C++模板和预处理宏
C++ templates and pre-process macro
请考虑以下代码
#include <iostream>
using namespace std;
template<int I>
int myfunc()
{
#if I
return 1;
#else
return 2;
#endif
};
int main()
{
cout<<myfunc<0>()<<endl;
cout<<myfunc<1>()<<endl;
}
但输出是
2
2
这样做的动机如下:
我有一个算法,需要在双点和定点中实现。一种解决方案是使用头文件根据宏标志定义数据类型,例如,
#ifdef __DOUBLE__
typedef double InputType;
.... // a lot of other types
typedef double OutputType;
#else //Fixed Point
typedef int InputType;
... // a lot of other types, which are matching with "__DOUBLE__" section
typedef int OutputType;
这种类型的解决方案的缺点是无法在运行时比较这两种实现。您必须相应地设置宏两次,编译两次,运行两次,然后比较收集的数据。理想情况下,我希望有一个带有非类型参数的模板函数或模板类,这允许我在实现之间切换
任何其他方法都可以实现类似的目标(在运行时比较两个实现)也是受欢迎的!
谢谢
选项:模板专用化
您可以专用化模板以允许单独的实现。模板专业化也可以为类完成。考虑:
template<typename T>
void foo(T) {
//general implementation
}
template<>
void foo(double d) {
//do something special for doubles
}
template<>
void foo(float f) {
//do something else for floats
}
选项:类型枚举
这类似于OpenGL。像这样:
enum MyTypes {FLOAT, DOUBLE};
void foo(MyType _m) {
//do some generic stuff
switch(_m) {
case FLOAT:
//do something for float
break;
case DOUBLE:
//do something else for float
break;
default:
//runtime error
}
//do some other stuff
}
但它将参数而不是模板参数引入函数。
相关文章:
- 错误:无效的预处理指令 #i 的意思是 #if?
- C++预处理会生成变量成员、资源库和映射
- 使用预处理指令检查是否包含标头?
- 预处理的 C/C++ 文件是否特定于计算机?
- 使用 GCC 对 C 文件进行部分预处理(不删除 "define" 指令)
- 在 CPLEX 中求解线性规划,无需剪切和预处理
- CPP -D 选项,用于预处理 Fortran 代码
- 错误:粘贴"tmp_UINT"和"+"未提供有效的预处理令牌
- 任务计划程序库的预处理不起作用 - 多定义错误
- Eclipse 问题 - 编译期间不考虑 .c 和 .cpp 文件中定义的预处理
- 使用python预处理后,C++(opencv)中的垫子类型数据与image_to_array相同
- Howo 使用 cl 预处理为 masm 组装生成一个单独的文件
- 我有一个预处理的 C/C++ 源文件 (cacti.i).如何从这个 .i 文件生成可执行二进制文件,以便我可以像 ./
- 如何使用Visual Studio C/C++编译器(cl.exe)来预处理我的objective-C代码
- 是具有预处理前分支实现的结构违反ODR
- 与不完整的Cholesky预处理的共轭梯度返回特征库的意外错误
- Visual Studio C - 无法输出预处理文件
- 在海湾合作委员会中加快宏观预处理的任何方法
- Xmllint未设置,而在路径中找不到XMLLINT;跳过XML预处理
- 如何在预处理时读取文件