我正在尝试设计一个标记指针类,其中指针的最低有效位可用作标志,但仅当它实际可用时,即指向类型的对齐方式大于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'
};
有没有办法实现我想要的?也许有不同的设计?
答案 0 :(得分:0)
这会放松吗?做法适合你?
.dll