I am writing a template class that manages a union of 2 classes. All the functions are pretty simple except the Get()
functions. It looks like this:
UnionPair.hpp
template <class First, class Second>
class UnionPair {
public:
UnionPair() : state_(State::kEmpty){};
~UnionPair(){};
void Reset();
void Set(std::unique_ptr<First>&& first);
void Set(std::unique_ptr<Second>&& second);
template <First>
First *Get();
template <Second>
Second *Get();
private:
enum class State { kEmpty, kFirst, kSecond } state_;
union {
std::unique_ptr<First> first_;
std::unique_ptr<Second> second_;
};
};
UnionPair.cpp
template <class First, class Second>
template <First>
First *UnionPair<First, Second>::Get() {
return first_.get();
}
template <class First, class Second>
template <Second>
Second *UnionPair<First, Second>::Get() {
return second_.get();
}
I'm trying to make the Get()
functions template methods that can only be called with the template classes of it's instantiated UnionPair
object, so that they can be overloaded by the template class they're called with. The above code does not compile.
My idea of how it would be called is this, but I get a compiler error when I try to call them:
// Definitions of structs A, B and C here
UnionPair<A, B> pair;
pair.Set(std::unique_ptr(new A()));
pair.Get<A>(); // should return a pointer to A (causes a compiler error right now)
pair.Get<C>(); // should cause a compiler error
I'm not really sure how to implement this method in the .cpp file, or if it's even possible. I've been reading about specialization within templates, but haven't seen any examples similar to mine, or examples where the specialization class MUST be the same as the object's template classes.
What is wrong with my usage/definition? Is what I'm trying to do possible? If not, are there any alternatives? What I DON'T want to do is have a seperate getter for First and Second like First *GetFirst()
because that relies on the order of the classes in the object instantiation and isn't clear.
Side note: If there is a c++ library that manages the state, setting and getting of union members I'd consider using it, but I'd still like to figure my question out.