Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6171113
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T23:09:31+00:00 2026-05-23T23:09:31+00:00

I’m transferring a project from Java to C++ and I have a problem with

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T23:09:32+00:00Added an answer on May 23, 2026 at 11:09 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a text area in my form which accepts all possible characters from
I have just tried to save a simple *.rtf file with some websites and
I am currently running into a problem where an element is coming back from
I have a bunch of posts stored in text files formatted in yaml/textile (from
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
this is what i have right now Drawing an RSS feed into the php,
Seemingly simple, but I cannot find anything relevant on the web. What is the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.