gpt4 book ai didi

c++ - 基于 alignof 的标记指针特化

转载 作者:太空宇宙 更新时间:2023-11-04 13:11:35 25 4
gpt4 key购买 nike

我正在尝试设计一个标记指针类,其中指针的最低有效位可用作标志,但前提是它实际可用,即指向类型的对齐大于 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>
}
};

关于c++ - 基于 alignof 的标记指针特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39568884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com