Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Achieving 'bounded genericity' in C++

I'm transferring a project from Java to C++ and I have a problem with something relatively simple in Java.

I have a class X which is made to handle objects of type Y and objects inherited from Y. X often need to call a method from Y, say kewl_method(), and this method is different in each class inherited from Y. In Java I could do something like this:

public class X<y extends Y>

I would call kewl_method() in X without any headache and it would do what I want. If I understand correctly (I'm new to C++), there is no such thing as bounded genericity in C++, so if I use a template with X it would be possible to fill it with absolutely anything and I won't be able to call the variants of kewl_method().

What is the best way to do this in C++ ? Using casts ?

Restriction: I cannot use boost or TR1.

like image 678
PhDP Avatar asked Jul 23 '11 20:07

PhDP


1 Answers

TravisG (was: heishe) already answered, as far as I am concerned.

But I want to comment on your question:

so if I use a template with X it would be possible to fill it with absolutely anything

No, because it wouldn't compile without an accessible kewl_method.

You have to remember that in Java, bounded genericity is less about limiting the types accepted by your generic class as you seem to believe, and more about giving the generic class a more complete information on its generic type T to be able to validate the call to its methods at compile time.

In C++, this feature is provided as-is and where-used by the compiler: In a way similar to duck typing, but resolved at compile-time, the compiler will accept the compilation of the method only if the generic type class has access to the kewl_method.

For an example of 4 classes:

class X
{
    public : virtual void kewl_method() { /* etc. */ }
} ;

class Y : public X
{
    public : virtual void kewl_method() { /* etc. */ }
} ;

class Z
{
    public : virtual void kewl_method() { /* etc. */ }
} ;

class K
{
    public : virtual void wazaa() { /* etc. */ }
} ;

Normal C++ solution

With C++ templates, you can feed your templated class A:

template<typename T>
class A
{
    public :
        void foo()
        {
            T t ;
            t.kewl_method() ;
        }
} ;

... with the class X, Y and Z, but not K, because :

  • X : it implements kewl_method()
  • Y : it publicly derives from X, which implements kewl_method()
  • Z : it implements kewl_method()
  • K : it doesn't implements kewl_method()

... which is much more powerful than Java's (or C#'s) generics. The user code would be :

int main()
{
    // A's constraint is : implements kewl_method
    A<X> x ; x.foo() ; // OK: x implements kewl_method
    A<Y> y ; y.foo() ; // OK: y derives from X
    A<Z> z ; z.foo() ; // OK: z implements kewl_method
    A<K> k ; k.foo() ; // NOT OK : K won't compile: /main.cpp error:
                       //   ‘class K’ has no member named ‘kewl_method’
    return 0;
}

You need to call the foo() method to block the compilation.

What if constraints are really needed?

If you want to limit it explicitly to classes inheriting from X, you must do it yourself, using code (until the C++ concepts are standardized... They missed the C++0x deadline, so I guess we will have to wait for the next standard...)

If you really want to put constraints, there are multiple ways. While I know about it, I'm not familiar enough with the SFINAE concept to give you the solution, but I can still see two ways to apply constraints for your case (while they were tested for g++ 4.4.5, could someone wiser validate my code?):

Add a unused cast?

The B class is similar to the A class with one additional line of code:

template<typename T> // We want T to derive from X
class B
{
    public :
        void foo()
        {
            // creates an unused variable, initializing it with a
            // cast into the base class X. If T doesn't derive from
            // X, the cast will fail at compile time.
            // In release mode, it will probably be optimized away
            const X * x = static_cast<const T *>(NULL) ;

            T t ;
            t.kewl_method() ;
        }
} ;

Which, when B::foo() is called, would compile only if T* can be cast into X* (which is only be possible only through public inheritance).

The result would be :

int main()
{
    // B's constraint is : implements kewl_method, and derives from X
    B<X> x ; x.foo() ; // OK : x is of type X
    B<Y> y ; y.foo() ; // OK : y derives from X
    B<Z> z ; z.foo() ; // NOT OK : z won't compile: main.cpp| error:
                       //      cannot convert ‘const Z*’ to ‘const X*’
                       //      in initialization
    B<K> k ; k.foo() ; // NOT OK : K won't compile: /main.cpp error:
                       //      cannot convert ‘const K*’ to ‘const X*’
                       //      in initialization
    return 0 ;
}

But, as the A example, you need to call the foo() method to block the compilation.

Add a homegrown "constraint" with a class?

Let's create a class expressing a constraint on its constructor:

template<typename T, typename T_Base>
class inheritance_constraint
{
    public:
        inheritance_constraint()
        {
            const T_Base * t = static_cast<const T *>(NULL) ;
        }
} ;

You'll note the class is empty, and its constructor does nothing, so chances are good it will be optimized away.

You would use it as in the following example:

template<typename T>
class C : inheritance_constraint<T, X> // we want T to derive from X
{
    public :
        void foo()
        {
            T t ;
            t.kewl_method() ;
        }
} ;

The private inheritance means your "inheritance_constraint" would not screw with your code, but still, it expresses at compile time a constraint that would stop the compilation for a class T that don't derives from X:

The result would be :

int main()
{
    // C's constraint is : implements kewl_method, and derives from X
    C<X> x ; // OK : x is of type X
    C<Y> y ; // OK : y derives from X
    C<Z> z ; // NOT OK : z won't compile: main.cpp error:
             //      cannot convert ‘const Z*’ to ‘const X*’
             //      in initialization
    C<K> k ; // NOT OK : K won't compile: /main.cpp error:
             //      cannot convert ‘const K*’ to ‘const X*’
             //      in initialization
    return 0 ;
}

The problem is that it relies on inheritance and constructor call to be effective.

Add a homegrown "constraint" with a function?

This constraint is more like a static assert, tested when the method is called. First, the constraint function:

template<typename T, typename T_Base>
void apply_inheritance_constraint()
{
    // This code does nothing, and has no side effects. It will probably
    // be optimized away at compile time.
    const T_Base * t = static_cast<const T *>(NULL) ;
} ;

Then the class using it:

template<typename T>
class D
{
    public :
        void foo()
        {
            // Here, we'll verify if T  inherits from X
            apply_inheritance_constraint<T, X>() ;

            T t ;
            t.kewl_method() ;
        }
} ;

int main()
{
    // D's constraint is : implements kewl_method, and derives from X
    D<X> x ; // OK : x is of type X
    D<Y> y ; // OK : y derives from X
    D<Z> z ; // NOT OK : z won't compile: main.cpp error:
             //      cannot convert ‘const Z*’ to ‘const X*’
             //      in initialization
    D<K> k ; // NOT OK : K won't compile: /main.cpp 2 errors:
             //      ‘class K’ has no member named ‘kewl_method’
             //      cannot convert ‘const K*’ to ‘const X*’
             //      in initialization
    return 0 ;
}

But, as the A and B example, you need to call the foo() method to block the compilation.

Conclusion

You'll have to choose between one of the methods above, according to your specific needs.

But usually, as far as I am concerned, I find all this quite overkill, and I would use the first, simpler solution above.

Edit 2011-07-24

Added another section with the code to express the constraint through a simple function call.

In the "Add a unused cast?" section, I replaced the reference cast X & x = t ; with the pointer cast (as in the other sections), which I believe is better.

And to give Caesar its due, the pointer cast was originally inspired by a line of code in the now deleted answer of Jonathan Grynspan.

like image 135
paercebal Avatar answered Oct 23 '22 12:10

paercebal