c++ - 具有条件类型名的模板类

标签 c++ class c++11 templates class-template

我想拥有一个模板类(例如float/double类型),但是我正在使用Nvidia CUDA和OptiX并具有多种其他类型(例如float2double2float3等),具体取决于所选的模板类型。
像这样:

#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/

相关文章:

C# 解释器。用于 C++ 中的事件形状模型库

ruby - 如何实现 Watir 类(例如 PageContainer)?

python - __init__ 和 __call__ 有什么区别?

c++ - 使用 C++ lambda 正确实现 finally block

c++ - 指向非指针编译错误的唯一指针

c++ - 最快的算法计算数组中 3 个长度 AP 的数量

c++ - 有没有直接的方法来连接两个字符数组 (char*)?

c++ - 数组错误

python - 在 Python 中,如果给出错误的参数,则返回 “None” 而不是创建新实例

c++ - 我需要 std::atomic<bool> 还是 POD bool 足够好?