我有一个使用静态列表(本例中为firstFriend)或动态列表(本例中为secondFriend)进行初始化的类。我不想在示例中编写列表功能,因为它并不重要。关键问题是firstFriend和secondFriend是好朋友。类"target“的构造函数的代码是相同的:如果我重载这些构造函数,我就会复制完全相同的代码。我不能给构造器设置模板,因为它不工作。
下面是示例(注意: firstFriend和secondFriend可能看起来是一样的,但在实际代码中却不一样,这只是一个大大简化的模型,它们的属性和功能之间的差异在“目标”类构造函数中没有任何区别,因为公共接口的部分是从两个完全相同的类中使用的):
template <class T>
class firstFriend
{
public:
firstFriend() {};
firstFriend(const T& t) {};
private:
T tAttribute;
};
template <class T>
class secondFriend
{
public:
secondFriend() {};
secondFriend(T t) : tAttribute(t) {};
friend class firstFriend<T>;
private:
T tAttribute;
};
class target
{
public:
target(const firstFriend<int>&)
{
// Some nice initialization of the TargetData.
}
target(const secondFriend<int>&)
{
// Exactly the same initialization as above.
// To the single character.
};
private:
firstFriend<int> TargetData;
};问:如何在不编写(复制/粘贴)相同代码的情况下重载构造函数?我尝试过将构造器模板化,但它不起作用。也许是隐式强制转换?最有效的方法是什么( firstFriend和secondFriend是巨大的数据列表)。提前感谢!
发布于 2011-04-12 21:18:41
如果两个构造函数具有完全相同的代码,则可以编写构造函数模板,如下所示:
template<class FriendType >
target(const FriendType &)
{
// Some nice initialization of the TargetData.
}如果有一点不同,但大部分代码是相同的,那么您可以编写一个init模板函数,并从两个构造函数中调用它,如下所示:
target(const firstFriend<int>& arg)
{
init(arg);
//other code
}
target(const secondFriend<int>& arg)
{
init(arg);
//other code
}
private:
template<class FriendType >
void init(const FriendType &)
{
//common code
}https://stackoverflow.com/questions/5635750
复制相似问题