The application I have in mind is something akin to a Vector<size>
class, in which I wish to declare
CrossProduct(const Vector<size>& other)
only for when size is 3. I know there are ways I can hack around it...
Is there any way to properly only declare the member function for a particular instantiation?
Here's one way to do it:
template <class Type, size_t Size>
struct EnableCrossProduct
{
};
template <class Type>
struct EnableCrossProduct<Type, 3>
{
void CrossProduct(const Type & other){}
};
template <size_t Size>
struct Vector : public EnableCrossProduct<Vector<Size>, Size>
{
};
If you can get the size info at compile-time, you can use std::enable_if.
template<int N>
struct Vector
{
static const int size = N;
double data[N];
// ...
template<class V>
double CrossProduct( const V& other,
typename std::enable_if< size == 3 && V::size == 3 >::type* = 0) const
{
// ...
return 0;
}
};
void foo( const Vector<3>& v3, const Vector<4>& v4 )
{
v3.CrossProduct( v3 ); // Ok
v3.CrossProduct( v4 ); // Compile-time error
}
You might just want to make that condition in the enable_if size == V::size
.
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