3

I have a base class with a virtual clone new method

class A
{
    virtual A* cloneNew() const { return new A; }
};

and its derivatives

class A1 : public A
{
    virtual A1* cloneNew() const { return new A1; }
};

class A2 : public A
{
    virtual A2* cloneNew() const { return new A2; }
};

Now I want to use macro or other way to make its re-implementation more easily like

class A1: public A
{
    CLONE_NEW; // no type A1 here
};

Is it possible to do it? Does decltype(this) help?

user1899020
  • 13,167
  • 21
  • 79
  • 154
  • Having a clone method is usually an indication of something wrong in the design (code smell). What are you really trying to do? – Martin York Oct 26 '13 at 14:53
  • 1
    @Loki Astari Can you elaborate on why a clone method is code smell? – Max Oct 26 '13 at 15:32
  • @LokiAstari I have dynamically-typed items in a tree of a GUI. I want to create a new similar item when an item is clicked. – user1899020 Oct 26 '13 at 15:50
  • It's not very C++ like (hence the code smell). Looks like something I would do in Java. Also see: http://stackoverflow.com/q/6626201/14065 – Martin York Oct 26 '13 at 18:35

1 Answers1

3

The following works fine for me, and can easily be turned into a macro:

struct Foo
{
    virtual auto clone() -> decltype(this)
    {
        return new auto(*this);
    }
};

If you want the clone() function to be const, you cannot use new auto and you have to work a bit harder with the return type:

#include <type_traits>

virtual auto clone() const -> std::decay<decltype(*this)>::type *
{
    return new std::decay<decltype(*this)>::type(*this);
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 1
    @user1899020 MSVC11 (The C++ compiler of VS2012) [does not support C++11 completely](http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx). On the other hand, as far I know MSVC11 supports trailing return type and the `decltype` specifier, so the problem should be at the implementation of `std::decay`. Whats exactly your compiler error? – Manu343726 Oct 26 '13 at 14:35
  • MSVC11 shows `this` can only be used in the internal body of non-static methods of a class. The problem is on `-> decltype(this)` – user1899020 Oct 26 '13 at 14:37
  • 1
    @user1899020 I have tried that in my VS2012 installation and fails too. Seems like a MSVC11 bug. – Manu343726 Oct 26 '13 at 14:48