Corecion Template Idiom (Template Copy-Constructor & Assignment Operator)

 

  Many programmers find that we can write a template constructor, but do Not know what the usage of. Let's see the coding below:

class Helper
{
public:
    template <typename U>
    Helper(const U &other){}        // Is it any meaningful? It's depends.
}

 

Intent:

#include <iostream>
using namespace std;

class B{};
class D : public B{};

template <typename T>
class Helper{};

int main()
{
    // 
    B *pB = NULL;
    D *pD = NULL;

    pB = pD;          // Ok.                                                       1)                     
// Helper<B> b; Helper<D> d; b = d; // Illegal. No assignment operator between these two types. 2)
    return 0;
}

  As in line 1), the pointer assignment from derived class to base class is legal and conversion is implicit.

  But it's useful when assigning to each other between composed type, such as 2).

 

Solution:

template <typename T>
class Helper
{
public:
    Helper(){}

    template <typename U>
    Helper(const U &other)
     : m_data(other.m_data) { cout
<<"ctor" <<endl; } template <typename U> Helper &operator=(const U &other) { //if (this != reinterpret_cast<Helper *>(&other)) illegal conversion. { Helper tmp(other); std::swap(m_data, tmp.m_data); } cout <<"cp-ctor" <<endl; return *this; } T *m_data; };

  As see, you have to provide a template copy constructor and template assignment operator.

posted @ 2012-09-13 10:24  walfud  阅读(256)  评论(0编辑  收藏  举报