dimanche 24 juillet 2016

Enabling a static member conditionally without changing the member scope

I want to enable a static member for a class without changing its scope. Consider the following abstracted example:

template<uint R, uint C>
class Foo
{
    static Foo ID;

    /* other members */
};

Now I want to use the static member like:

Foo<3, 3> foo = Foo<3, 3>::ID;

The problem is that the ID field can only exist when R == C.
(Foo is actually a Matrix and ID its identity which only exists for square matrices)

So I have to conditionally enable the static ID member when the condition is met. My current solution is something like this:

struct EmptyBase { };

template<uint R, uint C>
class _Foo_Square
{
    static Foo<R, C> ID;
};

template<uint R, uint C>
class Foo : public std::conditional<R == C, _Foo_Square<R, C>, EmptyBase>::type
{
    /* other members */
};

But now I cannot write Foo<3, 3>::ID to access it. I have to write _Foo_Square<3, 3>::ID.

Unfortunately the design of my application forces it to be accessible by the Foo class scope. If it wasn't a conditional member I could write using _Foo_Square<3, 3>::ID; in the Foo class.

Is there a solution to this problem?

Aucun commentaire:

Enregistrer un commentaire