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?
Function Templates with Multiple Parameters You can also use multiple parameters in your function template. The above syntax will accept any number of arguments of different types. Above, we used two generic types such as A and B in the template function.
Can there be more than one argument to templates? Yes, like normal parameters, we can pass more than one data type as arguments to templates.
A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.
For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.
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;
};
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; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With