Forwarding all constructors in C ++ 0x

What is the correct way to redirect all parent constructors in C ++ 0x?

I did it:

class X: public Super { template<typename... Args> X(Args&&... args): Super(args...) {} }; 
+17
c ++ constructor c ++ 11 templates
Jun 25 '10 at 17:05
source share
2 answers

In C ++ 0x there is a better way to do this

 class X: public Super { using Super::Super; }; 

If you declare a perfect forwarding pattern, your type will not work well when resolving overloads. Imagine your base class being converted from int and there are two functions for printing classes

 class Base { public: Base(int n); }; class Specific: public Base { public: template<typename... Args> Specific(Args&&... args); }; void printOut(Specific const& b); void printOut(std::string const& s); 

You call it with

 printOut("hello"); 

What will be called? This is ambiguous because Specific can convert any arguments, including arrays of characters. It does this without regard to existing base class constructors. Inheritance of constructors using declarations declares only the constructors needed to do the job.

+38
Jun 25 2018-10-25T00-06-25
source share

I think you need to do Super(std::forward<Args>(args)...) if you want everything to be sent correctly. args has a name, so I believe it links to regular links before rvalue links.

Moreover, you will not forward copy constructors in this way. The compiler will still generate one for you, because it does not consider template constructors. In the above example, you're fine because the compiler you just created will call the constructor of the parent copies, anyway, what exactly do you want. If this does not work in a more complicated case, then you will have to write it yourself.

+5
Jun 25 '10 at 17:26
source share



All Articles