基于alignof的标记指针专门化

tagged pointer specialization based on alignof

本文关键字:指针 专门化 alignof 基于      更新时间:2023-10-16

我试图设计一个标记的指针类,其中指针的最低有效位可用作标志,但只有当它实际可用时,即,指向类型的对齐大于1。

下面的工作,除了最后的问题,其中alignof()不能应用于不完整类型。

#include <cstdint> //for std::uintptr_t
template<typename T> struct always_tagged_pointer {
    static_assert(alignof(T) != 1, ""); //lsb available
    union { T* ptr; std::uintptr_t bits; };
    //rest of implementation omitted
};
template<typename T, size_t alignof_T> struct maybe_tagged_pointer_impl {
    static_assert(alignof(T) != 1, ""); //lsb available
    union { T* ptr; std::uintptr_t bits; };
    //rest of implementation omitted
};
template<typename T> struct maybe_tagged_pointer_impl<T, 1> {
    static_assert(alignof(T) == 1, ""); //lsb not available
    T* ptr; bool flag;
    //rest of implementation omitted
};
template<typename T> using maybe_tagged_pointer = maybe_tagged_pointer_impl<T, alignof(T)>;
maybe_tagged_pointer<int>  a; //OK.
maybe_tagged_pointer<char> b; //OK.
struct foo {
    int i; //so that alignof(foo)!=1 for this test
    void fun1(always_tagged_pointer<foo> p) {} //Ok.
    void fun2( maybe_tagged_pointer<foo> p) {} //error: invalid application of 'alignof' to an incomplete type 'foo'
};

有什么方法可以达到我想要的吗?也许是不同的设计?

这种"轻松"的方式适合你吗?

struct foo {
    int i; //so that alignof(foo)!=1 for this test
    void fun1(always_tagged_pointer<foo> p) {} //Ok.
    // with the discipline that the calling code will always pass a foo
    // for the U type, this may work
    template <type U> void fun2( maybe_tagged_pointer<U> p) {
       // will this create one more compile err??
       using dummy_t=std::enable_if<std::is_same<U,foo>::value>
    }
};