問題描述
在 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...) {}
};
推薦答案
C++0x 中有一個更好的方法來解決這個問題
There is a better way in C++0x for this
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
可以轉換任何參數,包括字符數組.它這樣做不考慮現有的基類構造函數.使用 using 聲明繼承構造函數僅聲明使此工作所需的構造函數.
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 中轉發所有構造函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!