#include <iostream>
#include <deque>
#include <list>
template<typename T>
class Holder
{
public:
Holder(){}
template<typename I>
Holder(I begin, I end)
: m_data(begin,end)
{ }
private:
typedef std::deque<T> Data;
Data m_data;
};
int main()
{
std::list<int> ints;
ints.push_back(3);
ints.push_back(4);
ints.push_back(5);
// Works implicitly:
Holder<int> HoldedInts(ints.begin(), ints.end());
Holder<int> *pHI_1 = new Holder<int>(ints.begin(), ints.end());
delete pHI_1;
// Does not work explicitly:
// Holder<int> HoldedInts<std::list<int>::const_iterator>(ints.begin(), ints.end());
// Holder<int> *pHI_1 = new Holder<int><std::list<int>::const_iterator>(ints.begin(), ints.end());
// delete pHI_1;
return 0;
}
2012-03-14
Invoking template constructor of a template class
2012-03-02
shared_ptr vs inheritance
A picture is worth a thousand words
#include <iostream>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
class A: public boost::enable_shared_from_this<A>
{
public:
typedef A Self;
typedef Self Root;
typedef boost::shared_ptr<Self> SPtr;
public:
A(){ std::cerr << "DEBUG: A::A()" << std::endl; }
virtual ~A(){ std::cerr << "DEBUG: A::~A()" << std::endl; }
SPtr getSPtr()
{
return shared_from_this();
}
};
class B: public A
{
public:
typedef B Self;
typedef A Base;
typedef Base::Root Root;
typedef boost::shared_ptr<Self> SPtr;
public:
B(){ std::cerr << "DEBUG: B::B()" << std::endl; }
virtual ~B(){ std::cerr << "DEBUG: B::~B()" << std::endl; }
SPtr getSPtr()
{
return boost::dynamic_pointer_cast<Self>(Root::getSPtr());
}
};
#define CHECKPOINT std::cerr << "CHECKPOINT: " __FILE__ " (" << __LINE__ << ")" << std::endl
int main()
{
CHECKPOINT;
A::SPtr spX(new A);
CHECKPOINT;
B::SPtr spY(new B);
CHECKPOINT;
return 0;
}
Compile!
g++ -W -Wall -Wextra -pedantic -Os shared_vs_inheritance.cpp -o shared_vs_inheritance
Run!
CHECKPOINT: shared_vs_inheritance.cpp (42) DEBUG: A::A() CHECKPOINT: shared_vs_inheritance.cpp (44) DEBUG: A::A() DEBUG: B::B() CHECKPOINT: shared_vs_inheritance.cpp (46) DEBUG: B::~B() DEBUG: A::~A() DEBUG: A::~A()
Subscribe to:
Comments (Atom)