转发所有构造函数在C ++ 0x [英] Forwarding all constructors in C++0x
问题描述
在C ++ 0x中转发所有父构造函数的正确方法是什么?
What is the correct way to forward all of the parent's constructors in C++0x?
我一直在做这个:
class X: public Super {
template<typename... Args>
X(Args&&... args): Super(args...) {}
};
推荐答案
class X: public Super {
using Super::Super;
};
如果你声明一个完美转发模板,你的类型将在重载分辨率上表现不佳。想象一下,你的基类可以从 int
转换,并且存在两个函数来打印类:
If you declare a perfect-forwarding template, your type will behave badly in overload resolution. Imagine your base class is convertible from int
and there exist two functions to print out 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);
您使用
printOut("hello");
要调用什么?这是不明确的,因为 Specific
可以转换任何参数,包括字符数组。它这样做,不考虑现有的基类构造函数。使用声明继承构造函数仅声明使此工作所需的构造函数。
What will be called? It's ambiguous, because Specific
can convert any argument, including character arrays. It does so without regard of existing base class constructors. Inheriting constructors with using declarations only declare the constructors that are needed to make this work.
这篇关于转发所有构造函数在C ++ 0x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!