Reputation: 5477
I have a class that uses either a static list (firstFriend in the example) or a dynamic list (secondFriend in the example) for initialization. The list functionality I didn't want to write for the example because it is not important. The key problem is that the firstFriend and the secondFriend are, well, friends. The code of the constructors of the class "target" is the same: if I overload the constructors I'm duplicating exactly the same code. I cannot template the constructors because it doesn't work.
Here's the example (NOTE: the firstFriend and secondFriend may look the same, but they are NOT the same in the ACTUAL code, this is just a heavily reduced model, the differences between their attributes and functionality does not make any differrence in the "target" class constructor because the parts of the public interface is used from both classes that are exactly the same):
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;
};
Question: how do I overload constructors without writing (copy/paste-ing) the same code twice? I have tried templating the constructors, but it didn't work. Implicit cast maybe? What would be the most efficient way (the firstFriend and secondFriend are HUGE lists of data). Thanks in advance!
Upvotes: 3
Views: 1249
Reputation: 361612
If both constructors have exactly same code, then you can write a constructor template as:
template<class FriendType >
target(const FriendType &)
{
// Some nice initialization of the TargetData.
}
If there is a little difference, but most of the code is same, then you can write an init
template function, and call it from both constructors as:
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
}
Upvotes: 1