mercredi 25 février 2015

Variant implementation (variadic template) C++

I'm trying to implement a variant class but I'm having a problem with a recursive function:



template<typename Visitor, typename... Types>
class VariantVisitor;

template<typename... Types>
class Variant
{
template <typename V, typename... types>
friend class VariantVisitor;
public:
struct holder
{
virtual ~holder() {}
};

template <typename T>
struct impl : public holder
{
impl(const T& t) : val(t) {}
T get() const { return val; }
T val;
};

Variant() : mHolder(nullptr) {}

template <typename T>
Variant(const T& t)
{
mHolder = new impl<T>(t);
}

Variant(const Variant<Types...>& v) : mHolder(nullptr)
{
copy<Types...>(v);
}

~Variant()
{
delete mHolder;
}

template <typename T>
Variant<Types...>& operator = (const T& t)
{
if (!mHolder) {
mHolder = new impl<T>(t);
return *this;
}

_ASSERT(typeid(*mHolder) == typeid(impl<T>));
static_cast<impl<T>*>(mHolder)->val = t;
return *this;
}

Variant<Types...> &operator = (const Variant& v)
{
copy<Types...>(v);
return *this;
}

template <typename T>
T Get() const
{
_ASSERT(mHolder && typeid(*mHolder) == typeid(impl<T>));
return static_cast<impl<T>*>(mHolder)->get();
}

template<typename T>
bool Is() const
{
return (mHolder && typeid(*mHolder) == typeid(impl<T>));
}
private:
template <typename T>
void copy(const Variant<Types...>& v)
{
if (mHolder) delete mHolder;
impl<T>* ptr = static_cast<impl<T>*>(v.mHolder);
mHolder = new impl<T>(*ptr);
}

template <typename T, typename...types>
void copy(const Variant<Types...>& v)
{
if (!Is<T>())
return copy<types...>(v);

copy<T>(v);
}

holder* mHolder;
};


Visual C++ 2013 says there is an ambiguous call to this line:



copy<T>(v);


I'm new to variadic templates but I think it should distinguish the two copy functions for the number of types, shouldn't it? So why they can be both overloads? And, of course, how can I fix this?


Aucun commentaire:

Enregistrer un commentaire