2013-07-29 64 views
1

編輯更新的代碼:
爲什麼模板複製構造函數會覆蓋默認的複製構造函數?

class Any 
{ 
public: 
    Any() 
    { 
    } 

    Any(const Any &other) 
    { 

    } 

    Any(Any &other) // added per Ben's answer 
    { 
    } 

    Any(Any &&other) 
    { 
    } 

    Any(const char *value) 
    { 
    } 

    template<typename T> 
    Any(const T &value) 
    { 
    } 

    template<typename T> 
    Any(T &&value) 
    { 
     cout << "move ctor" << endl; 
    } 

    template<typename T> 
    Any(const vector<T> &value) 
    { 
    } 

    template<typename T> 
    Any(vector<T> &&value) 
    { 
    } 
}; 

int main(int argc, char *argv[]) 
{ 
    vector<string> numbers; 
    numbers.push_back("one"); 
    numbers.push_back("two"); 
    numbers.push_back("three"); 
    numbers.push_back("four"); 

    Any anyNumbers(numbers); 
    Any anyNumbersCopy = anyNumbers; 

    return 0; 
} 


打印:

「移動男星」

這究竟是爲什麼?

有沒有什麼辦法來強制默認的拷貝構造函數被調用,而不是模板常量&構造?

我想避免使模板的構造明確如果可能的話,這樣我仍然可以暗中構建這樣的類;

Any number = 5; 
+3

提供一個展示問題的SSCCE。重載更喜歡非模板到模板。 –

+0

的http://stackoverflow.com/questions/9487821/why-cant-i-override-the-default-copy-constructor-and-assignment-operator-with-t?rq=1 – WhozCraig

+1

,還有可能重複沒有像「模板拷貝構造函數」這樣的東西。您的模板函數定義了一系列轉換構造函數,包括從'const Any&'轉換,但不是複製構造函數。 –

回答

5

也許你的真實代碼看起來更像這樣嗎?

class Any 
{ 
public: 
    Any(){} 

    Any(const Any &other) 
    { 
    } 

    template<typename T> 
    Any(T &&other) 
    { 
    } 
}; 

在這種情況下,模板是Any& other更好的匹配(不const!)。然後,解決方案是提供一個非常量非模板拷貝構造函數過載:

class Any 
{ 
public: 
    Any(){} 

    Any(const Any &other) 
    { 
    } 

    Any(Any &other) 
    { 
    } 

    template<typename T> 
    Any(T &&other) 
    { 
    } 
}; 
+0

就是這樣。使用非const拷貝構造函數會產生正確的行爲。現在,我得到一個編譯器警告,雖然:警告C4521:「任何」:多個拷貝構造函數指定 – bitwise

+0

不錯的猜測BTW =) – bitwise

+0

科12.8p4的標準特別允許其在一個類的拷貝構造函數的多種形式......我建議禁用該警告。 –

相關問題