Search code examples
c++classc++11templatesclass-template

Template class with conditional typenames


I would like to have a template class (e.g. float/double type), but I am using Nvidia CUDA and OptiX and have multiple other types (e.g. float2, double2, float3,...) that depend on the chosen template type.

Something like this:

#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; 
   };
};

My solution for now is to have multiple template arguments MyClass<T,T2,T3> my_object;, but this seems to have too much overhead and clutter. Is there a way to achieve the same with a single template argument as desired above?


Solution

  • Typically you'd do this by creating a trait type whose specializations define the additional types. For example:

    // 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
    };
    

    Then you can alias from these types to a name in your type, if desired:

    template <typename T>
    class MyClass {
    public:
        using T2 = typename optix_traits<T>::dim2;
    };