问题描述
我正在为 Variant 类编写一个简单的实现,但是当我尝试实例化 AlignedStorage 类型的变量时,Visual Studio 拒绝了此代码:
using std::size_t;
template <size_t SIZE,size_t... ALIGNMENT>
struct AlignedStorage
{
struct Type
{
alignas(ALIGNMENT...) unsigned char storage[SIZE];
};
};
template <size_t SIZE,size_t... ALIGNMENT>
using AlignedStorageT = typename AlignedStorage<SIZE,ALIGNMENT...>::Type;
/**** variant storage class ****/
template <typename... Types>
class VariantStorage
{
public:
void *GetStorage() { return mStorage.storage; }
const void *GetStorage() const { return mStorage.storage; }
template <typename T>
T &GetStorageAs() { return *reinterpret_cast<T*>(GetStorage()); }
template <typename T>
const T &GetStorageAs() const { return *reinterpret_cast<const T*>(GetStorage()); }
unsigned GetDiscriminator() const { return mDiscriminator; }
void SetDiscriminator(unsigned discriminator) { mDiscriminator = discriminator; }
private:
using LargestT = typename LargestType<Typelist<Types...>>::Type;
AlignedStorageT<sizeof(LargestT),alignof(Types)...> mStorage; ///////// Visual studio ERROR (not GCC)
unsigned int mDiscriminator; // discriminated union tag
};
它似乎与 ALIGNMENT 包扩展有问题,Gcc 似乎工作正常,但它拒绝了另一行(对于 VC++ 似乎没问题):
template <typename T,typename V> // CRTP
class VariantChoice;
template <typename...>
class Variant;
template <typename Type,typename... Types>
class VariantChoice<Type,Variant<Types...>>
{
friend class Variant<Types...>; // private ctor
protected:
static constexpr unsigned int mDiscriminatorIndex = IndexOfType<Type,Typelist<Types...>>::Value; // index of Type in typelist
private:
VariantChoice() = default;
~VariantChoice() = default;
VariantChoice(const VariantChoice &other);
VariantChoice(VariantChoice &&other);
VariantChoice &operator=(const VariantChoice &other);
VariantChoice &operator=(VariantChoice &&other);
using Derived = Variant<Types...>; // CRTP
Derived &AsDerived() { return static_cast<Derived&>(*this); }
const Derived &AsDerived() const { return static_cast<Derived const&>(*this); }
};
/**** variant class ****/
template <typename... Types>
class Variant : VariantStorage<Types...>,VariantChoice<Types,Variant<Types...>>...
{
template <typename,typename>
friend class VariantChoice; // enable CRTP (private inheritance)
public:
using VariantChoice<Types,Variant>::VariantChoice...; // inherited ctors
Variant() {}
Variant(const Variant &other);
Variant(Variant &&other);
template <template <typename...> class Variant_,typename... Types_>
Variant(Variant_<Types_...> &&other);
using VariantChoice<Types,Variant>::operator=...; ///////// GCC ERROR: bring copy/move assignment operators in scope doesn't compile ???? (VC++ works)
Variant &operator=(Variant const &other);
Variant &operator=(Variant &&other);
private:
};
这个代码正确吗?还是我在做不标准的事情?
编辑 我更正了 alignof(Types)...
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)