ENIGMA Forums

General fluff => Off-Topic => Topic started by: Ideka on September 26, 2013, 11:53:07 pm

Title: Check it out: The craziest shit I've ever done in C++
Post by: Ideka on September 26, 2013, 11:53:07 pm
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.
Title: Re: Check it out: The craziest shit I've ever done in C++
Post by: DaSpirit on September 27, 2013, 12:17:59 pm
Your compiler did not blow up? I do not see why this would even be useful.
Title: Re: Check it out: The craziest shit I've ever done in C++
Post by: Goombert on September 27, 2013, 02:04:29 pm
Hai Ideka, long time no see :) Sorry if I am being lazy responding to you guys today.
Title: Re: Check it out: The craziest shit I've ever done in C++
Post by: Ideka on September 27, 2013, 02:38:48 pm
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.
Title: Re: Check it out: The craziest shit I've ever done in C++
Post by: DaSpirit on September 27, 2013, 05:35:50 pm
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.
Title: Re: Check it out: The craziest shit I've ever done in C++
Post by: Ideka on September 28, 2013, 02:06:17 am
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 (http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern). Guess it's not that crazy after all.