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, 그래,하지만 T = 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); 
}