根据模板参数选择宏定义
Selecting macro definitions based on template argument
我正在使用外部库从从模板构造的数据存储对象写入二进制数据。这是一个一般性问题,所以我不会在这里提到图书馆。模板是显式实例化的,因此它们只能是float
或double
类型。我将对库编写器的调用包装在我自己的方法中,该方法需要决定从库编写器请求的精度。当然,这取决于正在使用的类的版本。我不能使用这样的条件:
typedef std::conditional<std::is_same<T, float>::value, MACRO_FLOAT_TYPE, MACRO_DOUBLE_TYPE>::type T1;
因为我不想定义类型,所以我只想在下面的示例中定义precisionType
的值:
template <typename T>
class Data
{
// My class which can either contain data as float or double precision
// My wrapper for the library writing method which takes a custom typedef
void writeData(customType precisionType);
}
int main()
{
// Assume I need two different versions of the data store
Data<float> * dFloat = new Data<float>();
Data<double> * dDouble = new Data<double>();
// I have to call
dFloat->writeData(MACRO_TYPE_FLOAT);
dDouble->writeData(MACRO_TYPE_DOUBLE);
}
但是,我想向用户隐藏这个宏参数,因为它取决于所使用的库,将来可能会有所不同。
我想使precisionType
成为在扩展模板时编译时选择的类的私有常量成员。然后,用户可以只调用->writeData()
,而不必担心精度类型参数。我怎样才能做到这一点?
遇到这个答案并得到@NathanOliver的一些提示后,我意识到std::is_same()
可以用来解决问题。在Data
类中创建customType
的私有 const 成员并通过初始化器列表进行分配,然后只需在writeData()
中使用它,而无需使用参数。
template <typename T>
class Data
{
// My class which can either contain data as float or double precision
const customType dataType;
Data() : dataType(std::is_same<T, float>::value ? MACRO_TYPE_FLOAT : MACRO_TYPE_DOUBLE) {};
// My wrapper for the library writing method
void writeData() { // uses dataType internally };
}
int main()
{
// Assume I need two different versions of the data store
Data<float> * dFloat = new Data<float>();
Data<double> * dDouble = new Data<double>();
// I have to call
dFloat->writeData();
dDouble->writeData();
}
也许我误解了你的问题,也许我已经太久没有写任何C++了,但为什么你不能在类声明的方法签名中使用T
呢?
template <typename T>
class Data
{
writeData(T precisionType);
}
然后将其实例化为Data<float> * dFloat = new Data<float>();
将强制dFloat->writeData(floatVal);
仅接受float
类型的变量。
相关文章:
- C++宏定义和取消定义
- 根据 c++ 标准在该宏定义中推送/弹出宏时的行为是什么
- VS2017 #error: : snprintf 的宏定义与标准库函数声明冲突
- 宏定义不正确没有错误
- Visual Studio:snprintf 冲突的宏定义
- 宏定义中的预处理器令牌两边有两个双引号
- CMake 添加和删除宏定义以编译共享库/可执行文件
- 宏C++#定义示例(对象)(::f(s,(对象),arg1,arg2,arg3)
- 根据模板参数选择宏定义
- 使用宏定义打印格式参数
- 如何在Maya中选择自定义网格组件后立即发布用户事件
- 组合宏定义以一次获得多个定义 [avr C++]
- 如何在可执行文件中查看宏定义值
- 是否有另一种方法可以在不使用宏定义的情况下进行此操作
- 如何理解宏定义
- 坚持理解以下宏定义
- 发布C++宏定义
- 通过生成文件预处理器宏定义在 c++ 中无法正常工作
- 将预处理器宏定义为宏定义线
- GCC是否支持宏定义中的多行原始字符串文字