我有一个模板的问题,不知道有没有可能的方式来实现我想做的事。这是我的问题。模板类型名称问题
template <typename T>
class A
{
public:
typedef T* pointer;
typedef const pointer const_pointer;
A()
{}
template <typename D>
A(const D& d)
{
// how can I store the D type
// so I can refer it later on
// outside of this function
}
};
确定这里是什么,我想做一个更完整的代码(它可能不是编译)
class C
{
public:
virtual ~C(){}
virtual void* get_d() = 0;
private:
};
template <typename T, typename D>
class Cimpl : public C
{
public:
Cimpl()
:t()
,d()
{}
Cimpl(const T& t, const D& d)
:t(t)
,(d)
{}
void* get_d()
{
return &reinterpret_cast<D&>(d);
}
private:
T t;
D d;
};
class B
{
public:
B()
:p(0)
{}
template <typename T, typename D>
B(const T& t, const D& d)
:p(0)
{
try
{
p = new Cimpl<T, D>(t, d);
}
catch(...)
{
d(p);
}
}
void* get_d()
{
return (p != 0) ? p->get_d() : 0;
}
~B()
{
delete p;
}
private:
C* p;
};
template <typename T>
class A
{
struct example_d
{
};
public:
typedef T* pointer;
typedef const pointer const_pointer;
A()
{}
template <typename D>
A(const T& t)
:b(t, example_d())
{
}
template <typename D>
A(const T& t, const D& d)
:b(t, d)
{
// how can I store the D type
// so I can refer it later on
// outside of this function
}
// not type safe...as user can cast to any type
// if I can store the type user pass in previous
// then I can use it back
template <typename T>
T* get_d()
{
reinterpret_cast<T*>(b.get_d());
}
private:
B b;
};
所以我可以使用类像
1)A<int> a(1);// with example_d as D
2)A<int> b(1, another_d()) // with another_d
我可以将模板更改为2个参数,并将第2个类型的默认参数设置为example_d。所以我可以达到1)但不是2)。正如我将要编写这样
A<int, another_d> b(1, another_d());
有点太长型...
不能存储类型本身,但也有变通方法。你想用D做什么? – 2010-03-23 15:29:24
参数'T'有什么意义?这与问题有什么关系? – Seb 2010-03-23 15:30:11
我没有澄清我实际上想做什么。我想要一个类只需要一个模板参数。然后另一个模板类型提供参数构造函数。我可以在课程的其他部分使用D型,而不仅仅是类型D的通过 – stephenteh 2010-03-23 15:40:15