[ create a new paste ] login | about

Link: http://codepad.org/PW3MRt6h    [ raw code | output | fork ]

hecomi - C++, pasted on Apr 16:
// ----- vtableを使用したType Erasure2 -----
// επιστημη + 高橋 晶 著
// 『完結で再利用しやすいコードのためのC++活用術 C++テンプレートテクニック』より

#include <iostream>

const char* getTypeName(const int&)
{
	return "int";
}

const char* getTypeName(const float&)
{
	return "float";
}

class Base {
public:
	virtual ~Base() {}
};

template <class T>
class Derived : public Base {
	T value_;
public:
	Derived(const T& value) : value_(value) {}
	virtual ~Derived() {
		std::cout << getTypeName(value_) << std::endl;
	}
};

class X {
	Base* p_;
public:
	template <class T>
	X(const T& value_)
	{
		p_ = new Derived<T>(value_);
	}
		
	~X()
	{
		delete p_;
	}
};

int main()
{
	X x1(1);
	X x2(1.0f);
}


Output:
1
2
float
int


Create a new paste based on this one


Comments: