根据模板参数选择宏定义

Selecting macro definitions based on template argument

本文关键字:选择 宏定义 参数      更新时间:2023-10-16

我正在使用外部库从从模板构造的数据存储对象写入二进制数据。这是一个一般性问题,所以我不会在这里提到图书馆。模板是显式实例化的,因此它们只能是floatdouble类型。我将对库编写器的调用包装在我自己的方法中,该方法需要决定从库编写器请求的精度。当然,这取决于正在使用的类的版本。我不能使用这样的条件:

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类型的变量。