开发者

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.


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.


Just type it like this:

template<class T>
void method()
{
   T t;
   t.kewl_method();
}

If you use it in a wrong way, your compiler will give you an error saying, kewl_method() is not a member of [type of T].


If I understand you correctly making Y::kewl_method virtual would be a good translation from Java. You would than overload it in the classes derived from Y.


The construct you're referring to in Java is generics. The closest corresponding thing found in C++ is templates. So the closest translation of what you presented here in C++ would be

template<class T>
class X
{
    // Here you use T as Y or type derived from it
    // for example
    void method(T& y)
    {
        y.kewl_method();
    }
};

Usage is as follows:

X<Y> a;

Or if you have derived from Y type say Z:

class Z : public Y {
  // ...
};

You can as well use

X<Z> b;

This is acceptable. Templates are duck typed in C++, i.e. you can call any method of type T and it will be correct as long as the actually specified type has this method.


As I understand, you want to enforce that the template argument passed to your class template be inherited from a certain class Y. I should note that it is very unfortunate that you can't use boost. I'll provide a solution with boost.

template <class T, bool OK> class XImpl; //no definition, just declaration
template <class T> class XImpl<T, true> //partial specialization
{
    //here goes your real class definition
};
template <class T> class X : public XImpl<T, boost::is_base_and_derived<Y, T>::value >
{}; //if T isn't derived from Y, compilation will fail because you are trying to 
    //inherit from an incomplete (undefined) type 

The only boost part we used was is_based_and_derived metafunction. You can look in boost sources, see how it's implemented, and implement it yourself. HTH


Use a template but put a restriction on the types it work on:

template<typename T>
void
X::some_member(T& t)
{
    // Triggers a compile-time error if/when T is not derived from Y
    STATIC_ASSERT(( is_base_of<Y, T> ));
    t.kewl_method();
}

Since you're not using Boost you're going to have to implement STATIC_ASSERT and is_base_of. The first one is somewhat easy but the second one not as such (although you can use a convertible<T, Y> trait as an approximation).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜