嗯。。你这个似乎不需要吧data_t写这么复杂。。。
就是把指向数据的void*指针包装一下就好:class data_t
{
public:
template <typename T>
data_t(T& p) :value(&p) {};
template <typename T>
T access()
{
return *static_cast<T *>(this->value);
}
private:
void *value;
};
class IA
{
public:
virtual ~IA() {};
virtual uint64_t id() = 0;
virtual data_t get_data() = 0;
};
template <typename T>
class A : public IA
{
public:
A(const T &n) : data(n) {}
uint64_t id()
{
return uint64_t(this);
}
data_t get_data()
{
return data_t(data);
}
private:
T data;
};
int main(void)
{
IA *p = new A<int>(5);
std::cout << p->id() << std::endl;
std::cout << p->get_data().access<int>() << std::endl;
delete p;
p = new A<std::string>("fishc.com");
std::cout << p->id() << std::endl;
std::cout << p->get_data().access<std::string>() << std::endl;
std::string s = p->get_data().access<std::string>();
//int i = p->get_data().access<std::string>();
delete p;
system("pause");
}
|