У меня проблема с шаблоном, и мне интересно, есть ли способ достичь того, что я хотел сделать. Вот мой вопрос.
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 параметра, и использовать параметр по умолчанию для второго типа, который будет example_d. Так что я могу достичь 1), но не 2). Как мне придется кодировать этот путь
A<int, another_d> b(1, another_d());
слишком долго, чтобы напечатать ...