避免在专用模板中的代码重复 [英] Avoiding code duplication in a specialized template
本文介绍了避免在专用模板中的代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想有两个类似的模板,一个有一个参数,另一个有2个参数:
I want to have two similar templates, one with 1 parameter and other with 2 parameters:
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; }
};
注意所有T1相关的东西的代码重复。如何避免这种情况?
Notice the code duplication for all the T1-related stuff. How can I avoid this?
推荐答案
唯一的解决方案是在基类中尽可能多的代码。例如:
The only solution to this is to have as much code as possible in a base class. For example:
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) {}
};
这篇关于避免在专用模板中的代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文