我想拥有一个模板类(例如float
/double
类型),但是我正在使用Nvidia CUDA和OptiX并具有多种其他类型(例如float2
,double2
,float3
等),具体取决于所选的模板类型。
像这样:
#include <optixu/optixu_vector_types.h>
#include <type_traits>
template <class T>
class MyClass
{
MyClass()
{
if (std::is_same<T, float>::value)
{
typedef optix::float2 T2;
}
else if (std::is_same<T, double>::value)
{
typedef optix::double2 T2;
}
T2 my_T2_variable;
}
void SomeFunction()
{
T2 another_T2_variable;
};
};
我目前的解决方案是使用多个模板参数MyClass<T,T2,T3> my_object;
,但这似乎有太多开销和困惑。有没有一种方法可以通过上述所需的单个模板参数来实现?
最佳答案
通常,您可以通过创建一个特征类型来完成此任务,该特征类型的专业性定义了其他类型。例如:
// Base template is undefined.
template <typename T>
struct optix_traits;
template <>
struct optix_traits<float> {
using dim2 = optix::float2;
// etc
};
template <>
struct optix_traits<double> {
using dim2 = optix::double2;
// etc
};
然后,可以根据需要将这些类型的别名命名为您的类型中的名称:template <typename T>
class MyClass {
public:
using T2 = typename optix_traits<T>::dim2;
};
关于c++ - 具有条件类型名的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62770234/