条件付き型名を持つテンプレート クラス

通常、特殊化が追加の型を定義する特性型を作成することでこれを行います。例:

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

std::conditional を使用できます 、 <type_traits> から .

T2 が必要な場合 optix::float2 であること T == floatのとき それ以外の場合は optix::double2std::conditional を使用 .これは c++11 以降で利用可能で、型 T2 を解決します コンパイル時。

#include <type_traits>  // std::conditional, std::is_same

template <class T>
class MyClass
{
    using T2 = typename std::conditional<std::is_same<T, float>::value,
                                          optix::float2, optix::double2>::type;
    T2 my_T2_variable;

    // ... other code
};

(デモを見る)

@HikmatFarhat として 指摘、std::conditional ユーザーの間違いをキャッチしません。最初の条件のみをチェックし、false をチェックします。 case は型 optix::double2 を与えます .

もう 1 つのオプションは、一連の SFINAE ed 関数と decltype です。 T2 用のものに 次のように:

#include <type_traits>  // std::is_same, std::enable_if

template <class T> // uses if T == float and return `optix::float2`
auto typeReturn() -> typename std::enable_if<std::is_same<float, T>::value, optix::float2>::type { return {}; }

template <class T> // uses if T == double and return `optix::double2`
auto typeReturn() -> typename std::enable_if<std::is_same<double, T>::value, optix::double2>::type { return {}; }

template <class T>
class MyClass
{
    using T2 = decltype(typeReturn<T>()); // chooses the right function!

    T2 my_T2_variable;

    // ... other codes
};

(デモを見る)


テンプレートの特殊化を使用してメタ関数を実装し、標準 C++ 型を目的の「ランク」を持つ OptiX 型にマップします。

template <typename T, std::size_t N> struct optix_type;

template <> struct optix_type<float, 2> { using type = optix::float2; };
template <> struct optix_type<float, 3> { using type = optix::float3; };
template <> struct optix_type<double, 2> { using type = optix::double2; };
// ...

template <typename T, std::size_t N>
using optix_type_t = typename optix_type<T, N>::type;

これをクラス内で使用して、適切な型を簡単に取得できます:

template <class T>
class MyClass {
  using T2 = optix_type_t<T, 2>;
  MyClass() {
    T2 my_T2_variable;
    optix_type_t<T, 3> my_T3_variable;
  }
  void SomeFunction() { T2 another_T2_variable; };
};