Home > other >  Call templated class with multiple parameters with single parameter only
Call templated class with multiple parameters with single parameter only

Time:11-06

I have a class with multiple template parameters; let us say it looks something like this:

template <class T, class B>
struct Vector2 : B
{
    Vector2() noexcept;
    constexpr explicit Vector2(T a) noexcept;
}

Template parameter B always depends on T. For example if T is float B will be XMFLOAT2, if T is int B will be XMINT2. For this I created a template specialization:

template class Vector2<float, XMFLOAT2>;
template class Vector2<int32_t, XMINT2>;
template class Vector2<uint32_t, XMUINT2>;

The problem is that since B always depends on T, I want to call Vector<float> for example, and the expression should expand to Vector<float, XMFLOAT2>.

I thought of doing a typealias, however, I wouldn't be sure how to accomplish this, since it would need to be specialized again.

template<class T> using Vector2 = Vector2<T, ??>;

That doesn't really make sense...

How can I call a class with multiple template parameters using just a single parameter with the others being deduced? Or is there a different approach?

CodePudding user response:

You can create helper trait:

template <typename T>
struct vector_base_class;

template <> struct vector_base_class<float> { using type = XMFLOAT2; };
template <> struct vector_base_class<int32_t> { using type = XMINT2; };
template <> struct vector_base_class<uint32_t> { using type = XMUINT2; };

template <class T>
struct Vector2 : typename vector_base_class<T>::type
{
    Vector2() noexcept;
    constexpr explicit Vector2(T a) noexcept;
};

CodePudding user response:

As mentioned in a comment, you are probably looking for a trait:

template <typename T>
struct xm_from_T;

template <class T, class B = typename xm_from_T<T>::type>
struct Vector2 : B
{
    Vector2() noexcept;
    constexpr explicit Vector2(T a) noexcept;
};

Then specialize the trait:

template <> struct xm_from_T<float> { using type = XMFLOAT2; };
template <> struct xm_from_T<int32_t> { using type = XMINT2; };
template <> struct xm_from_T<uint32_t> { using type = XMUINT2; };
  • Related