Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare a function that belongs to a singular instantiation of a template class?

Tags:

c++

templates

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...

  • Include a function definition only for size=3
  • let all other sizes yield linker errors
  • Do a static assert at the start of the method to check if size is 3

Is there any way to properly only declare the member function for a particular instantiation?

like image 266
Dan M. Katz Avatar asked Mar 20 '13 19:03

Dan M. Katz


2 Answers

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>
{
};
like image 197
Ed Rowlett-Barbu Avatar answered Sep 20 '22 05:09

Ed Rowlett-Barbu


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.

like image 21
metal Avatar answered Sep 23 '22 05:09

metal