基于alignof的标记指针专门化
tagged pointer specialization based on alignof
我试图设计一个标记的指针类,其中指针的最低有效位可用作标志,但只有当它实际可用时,即,指向类型的对齐大于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>
}
};
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 为自己的智能指针专门化模板
- 为可转换为指针的迭代器专门化一个类
- 专门化指针的模板类
- C++:如何防止模板专门化指针
- 专门化成员指针模板参数解析
- 智能指针的模板专门化与普通指针完全相同
- c++模板方法专门化以返回指针或引用
- 指针类型的类模板专门化调用中没有匹配的函数
- 基于alignof的标记指针专门化
- C++模板专门化,对可以是指针或引用的类型调用方法
- 使用成员函数指针专门化模板类