实例化时静态断言模板类型的大小
Static assert the size of a template type on instantiation
我想在用static_assert
实例化时检查以下结构的大小,以约束未命名的struct
是紧密封装的,因此A
的大小等于sizeof(T) * 3
。
template <typename T>
struct A
{
union
{
struct { T a, b, c; };
T arr[3];
};
};
这可以通过完成
static_assert(sizeof(A<T>) == sizeof(T) * 3, "hey something went wrong");
但是
由于
A<T>
在其类定义中仍然是一个不完整的类型,将上述static_assert
放入类定义中不是一个选项带有
sizeof
的static_assert
不会在所有编译器(如Clang)中的未实例化函数内部求值,因此将其放入伪成员函数不是的选项将
static_assert
放在构造函数或析构函数中是一个解决方案,但在上面的例子中,不存在用户定义的构造函数(想想聚合),进一步想象多个构造函数的情况,在这种情况下,我将避免在所有构造函数中执行断言从另一个结构继承
A
,并在A
的定义中对其执行static_assert
将是一个解决方案,但我希望保持结构简单,而不会干扰辅助结构
我还缺少其他解决方案吗?
我决定取消删除这个问题,并保留它以备将来可能的解决方案
一个特殊的成员函数(几乎)可以保证实例化,它是析构函数:
~A() noexcept { static_assert(sizeof(A<T>) == sizeof(T) * 3, "hey something went wrong"); }
namespace my_private_impl{
struct impl_tag{};
template <typename T,typename tag>
struct A_impl{
static_assert(is_same<tag,impl_tag>{}(),"you evil cheater");
union{
struct { T a, b, c; };
T arr[3];
};
};
};
template<typename T>
using A=std::enable_if_t<
sizeof(my_private_impl::A_impl<T,my_private_impl::impl_tag>) == sizeof(T) * 3,
my_private_impl::A_impl<T,my_private_impl::impl_tag>
>;
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 私有类型的静态常量成员
- C++ 模板类型的静态 lambda 成员的构造
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 如何在没有实例的情况下获取非静态方法的类型?
- 值和类型的简洁双向静态 1:1 映射
- 静态自动 constexpr t = { "red" , "black" , "green" } 是什么类型;派生到?
- 非类类型表达式的静态类型与动态类型之间的差异
- 如何使用类型级函数动态创建静态类型?
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 指向 POD 类型的指针之间的静态转换与重新解释转换
- 为什么 std::bind 静态类型检查传递给函数的参数?
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 静态私有函数,模板化类型作为C++中的默认参数
- 从相同类型的静态成员进行类内初始化
- 在类定义中推导内联静态成员函数的返回类型
- 参考类型静态数据成员的问题可能是编译器错误
- 如何使用泛型在 C# 中将类型静态绑定在一起(如在 TypeToType <T>中)?
- double类型静态类成员的常量表达式初始化项