如何防止类型被用作结构/类中的成员变量类型
How to prevent type from being used as a member variable type in a struct/class?
我想创建一个只能作为完整类型使用的类型,而不能作为成员变量类型使用。
所以对于这样的T
类型是允许的:
T a;
^^^
int foo(T b);
^^^
struct C { int foo(T b); };
^^^
int main() { T c; }
^^^
但是这会导致编译时错误:
struct C { T a; };
^^^
我很想展示我迄今为止尝试过的任何东西,但是没有任何东西可以至少接近我需要的解决方案,对不起。
当然,我也接受证明这在c++中是不可能的答案。
为什么我需要这个?我想让smart pointer
不能是另一个物体的元素。防止循环依赖的糟糕方法…
你不能。从c++语法(重点是我的,为了清晰起见省略了不相关的部分)来看,函数的声明是:
function-definition:
decl-specifier-seqopt declarator ctor-initializeropt function-body
decl-specifier-seqopt declarator function-try-block
对于类,它是:
class-specifier:
class-head { member-specificationopt }
member-specification:
member-declaration member-specificationopt
access-specifier : member-specificationopt
member-declaration:
decl-specifier-seqopt member-declarator-listopt ;
function-definition ;opt
::opt nested-name-specifier templateopt unqualified-id ;
using-declaration
template-declaration
member-declarator-list:
member-declarator
member-declarator-list , member-declarator
member-declarator:
declarator pure-specifieropt
declarator constant-initializeropt
identifieropt : constant-expression
最后declarator
是:
declarator:
direct-declarator
ptr-operator declarator
direct-declarator:
declarator-id
direct-declarator ( parameter-declaration-clause ) cv-qualifier-seqopt
exception-specificationopt
direct-declarator [ constant-expressionopt ]
( declarator )
可以看到,可以用作函数参数的类型也可以用作类成员。
如果可以在类之外使用对象,则该对象可以是类的成员。我可以99.9%地肯定,你不能以任何方式阻止它(这并不限制你如何/在哪里可以以其他方式使用T
——显然,拥有一个私有构造函数会阻止它成为类的直接成员,但它也会限制它在你所展示的其他三个场景中使用)。
- 访问C++中的类型成员
- 具有 STL 向量类型成员的类的复制内存
- 重载具有 2 个相同数据类型成员的构造函数
- std::void_t 和嵌套的非类型成员
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 使用各种数据类型成员创建对象的简便方法
- 将类类型成员定义为公共和私有之间有什么区别?
- 结构类型成员的默认构造函数中的默认参数
- 如何传递模板模板非类型成员函数指针
- 文本类类型成员函数约束
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- C++:将模板参数的模板类型成员加为好友的语法正确吗
- C++静态结构类型成员初始化
- C++:作为引用或指针的基类型成员变量
- 左值引用类型成员的用户定义移动构造函数
- 具有指针类型成员的类在 MSVS2012@debug 下销毁时失败.程序错误或错误源
- CRTP -- 访问不完整的类型成员
- 为什么C++默认初始化不对非类类型成员进行零初始化
- 请求非类类型成员