【发布时间】:2020-12-15 23:27:06
【问题描述】:
是否可以避免为结构 A, Bstrong> 定义相同的函数两次?它们的成员名称完全相同,但 v0, v1 ... vN 成员在两个结构 A 和 B 之间的类型不同.如果有帮助,成员 v* 都来自同一个结构 V。
非平凡函数(即赋值 =)可以在结构外部重用模板化复制函数,如下所示,但如果在结构内定义一次,它会是首选/更清洁。
有没有一种简洁的方法可以将 A 和 B 定义模板化为一个定义?
template <class T1, class T2>
void copy(T1& to, T2& from)
{
to.v0 = from.v0;
to.v1 = from.v1;
to.type = from.type;
}
enum class E { TYPE_0, TYPE_1 };
struct B;
struct A
{
C0<float> v0;
C1<int> v1;
E type;
A& operator = (const B& t)
{
copy(*this, t);
return *this;
}
string strType() { return string(type); }
};
struct B
{
D0<float> v0;
D1<int> v1;
E type;
B& operator = (const A& t)
{
copy(*this, t);
return *this;
}
string strType() { return string(type); }
}
【问题讨论】:
标签: c++ class templates member-functions class-template