Pages: 1
  Print  
Author Topic: Check it out: The craziest shit I've ever done in C++  (Read 4490 times)
Offline (Unknown gender) Ideka
Posted on: September 26, 2013, 11:53:07 pm

Member
Joined: Apr 2011
Posts: 85

View Profile
Code: (cpp) [Select]
template <class T, class U> class SomeClass {
    public:
        // ...

        U some_method() {
            // ...
        }
}

class OtherClass : public SomeClass<YetAnotherClass, OtherClass> {  // !!!
    public:
        // ...
}

So it's a class that inherits from a template of another class and itself, so it can later return its own type. I couldn't believe it but it even works and everything.

And...
Yeah...
That's it.
Logged
Offline (Male) DaSpirit
Reply #1 Posted on: September 27, 2013, 12:17:59 pm

Member
Location: New York City
Joined: Mar 2013
Posts: 124

View Profile
Your compiler did not blow up? I do not see why this would even be useful.
Logged
Offline (Male) Goombert
Reply #2 Posted on: September 27, 2013, 02:04:29 pm

Developer
Location: Cappuccino, CA
Joined: Jan 2013
Posts: 2993

View Profile
Hai Ideka, long time no see :) Sorry if I am being lazy responding to you guys today.
Logged
I think it was Leonardo da Vinci who once said something along the lines of "If you build the robots, they will make games." or something to that effect.

Offline (Unknown gender) Ideka
Reply #3 Posted on: September 27, 2013, 02:38:48 pm

Member
Joined: Apr 2011
Posts: 85

View Profile
Hai Robert :P.

@DaSpirit: Here's more context so you see why I had to do it:
Code: (cpp) [Select]
template <class T, class U> class Image {
    public:
        // ...

        U cropping(int x, int y, uint width, uint height) {
            // ...
        }

        // ...

    protected:
        std::vector<std::vector<T> > grid;
}

class Surface : public Image<Tile, Surface> {
    // ...
}

class Layer : public Image<MapFeature, Layer> {
    // ...
}
If you think there's a better way of doing this I'm all ears.
Logged
Offline (Male) DaSpirit
Reply #4 Posted on: September 27, 2013, 05:35:50 pm

Member
Location: New York City
Joined: Mar 2013
Posts: 124

View Profile
I don't see why you made them need each other. So a surface always has one other surface? Doesn't make much sense to me.
Logged
Offline (Unknown gender) Ideka
Reply #5 Posted on: September 28, 2013, 02:06:17 am

Member
Joined: Apr 2011
Posts: 85

View Profile
It doesnt have a surface, it can return a surface (or rather, it can have its parent return a surface).

BTW turns out, this is actually a pattern: http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern. Guess it's not that crazy after all.
Logged
Pages: 1
  Print