2014-12-11 2 views
1

Почему делегирование конструкторов не выполняется в случае шаблонов? Конструктор копирования не вызывает конструктор константной копии в случае T=U, хотя без этого template <typename U> и <U> он работает.Делегирование конструкторов и шаблонов

template <typename T> 
struct Class { 
    Class() { 
     std::cout << "Default constructor" << std::endl; 
    } 
    template <typename U> 
    Class (const Class<U>& rhs) { 
     std::cout << "Const copy constructor" << std::endl; 
    } 
    template <typename U> 
    Class (Class<U>& rhs) 
     : Class (const_cast<const Class<U>&> (rhs)) 
    { 
     std::cout << "Copy constructor (templated)" << std::endl; 
    } 
/* // DOES NOT WORK WITHOUT THE NEXT: 
    Class (Class& rhs) 
     : Class (const_cast<const Class&> (rhs)) 
    { 
     std::cout << "Copy constructor (not templated)" << std::endl; 
    } 
*/ 
}; 
+2

[Работы для меня] (http://coliru.stacked-crooked.com/a/18c2a8ffd206f55f) –

+0

@AntonSavin, да, но не с Т = U. – se0808

+0

@ DieterLücking, даже без шаблона '? – se0808

ответ

2

Обратите внимание: конструктор шаблонов никогда не является (!) Конструктором копирования. Вместо этого будет создан конструктор копирования по умолчанию (если это возможно).

struct NoCopy 
{ 
    NoCopy() {} 
    NoCopy(const NoCopy&) = delete; 
}; 

template <typename T> 
struct Test 
{ 
    NoCopy member; 
    Test() {}; 

    template <typename U> 
    Test(const Test<U>&) 
    {} 
}; 

int main() 
{ 
    Test<int> a; 
    // The following error shows the missing generation of a default constructor, 
    // due to the non copyable member. Without that member, the code compiles. 
    // error: use of deleted function ‘Test<int>::Test(const Test<int>&)’ 
    Test<int> b(a); 
} 
Смежные вопросы