Museful
Museful

Reputation: 6959

Defining nested class conditionally based on enclosing class template parameters

A matrix has an LU factorization only if it is square (M==N). Is there a simple way to disable class lu and method luFactorization iff M!=N below?

template<int M, int N>
class matrix {

    // lots and lots of operators and stuff
    // ...

    class lu {
        // ...
    }

    lu luFactorization() {
        // ...
    }

}

Upvotes: 2

Views: 47

Answers (1)

davmac
davmac

Reputation: 20641

Define "simple". :)

Template partial specialisation does work:

template <int M, int N>
class matrix {
    // class lu, function luFactorization *not* defined
};

template <int N>
class matrix<N,N> {
    // class lu, function luFactorization defined
    class lu { };
    lu luFactorisation() { /* ... */ }
};

If there is a lot of baggage that both variants should have, you may be able to move some or all of that baggage to a common superclass. You might also consider making lu and luFactorisation non-member templates.

Upvotes: 5

Related Questions