我想要两个相似的模板,一个带有1个参数,另一个带有2个参数:
template<typename T1,typename T2=void> struct foo { T1 m_t1; T2 m_t2; foo(T1 t1,T2 t2) : m_t1(t1),m_t2(t2) {} T1 t1() { return m_t1; } T2 t2() { return m_t2; } }; template<typename T1> struct foo<T1,void> { T1 m_t1; foo(T1 t1) : m_t1(t1) {} T1 t1() { return m_t1; } };
@R_404_323@
解决此问题的唯一方法是在基类中拥有尽可能多的代码.例如:
template<typename T1> struct foo_base { T1 m_t1; explicit foo_base(T1 t1) : m_t1(t1) {} T1 t1() const { return m_t1; } }; template<typename T1,typename T2=void> struct foo : foo_base<T1> { T2 m_t2; foo(T1 t1,T2 t2) : foo_base<T1>(t1),m_t2(t2) {} T2 t2() const { return m_t2; } }; template<typename T1> struct foo<T1,void> : foo_base<T1> { explicit foo(T1 t1) : foo_base<T1>(t1) {} };