如何防止类型被用作结构/类中的成员变量类型

How to prevent type from being used as a member variable type in a struct/class?

本文关键字:类型 成员 变量 结构 何防止      更新时间:2023-10-16

我想创建一个只能作为完整类型使用的类型,而不能作为成员变量类型使用。

所以对于这样的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——显然,拥有一个私有构造函数会阻止它成为类的直接成员,但它也会限制它在你所展示的其他三个场景中使用)。