繁体   English   中英

有没有办法构建C ++自定义限定符?

[英]Is there a way to build C++ custom qualifiers?

有没有办法实现自定义类型限定符(类似于const)? 我想只允许函数调用具有相同资格的函数中具有相同资格的函数。

假设我会:

void allowedFunction();
void disallowedFunction();

//Only allowed to call allowed functions.
void foo()
{
    allowedFunction();
    disallowedFunction(); //Cause compile time error
}

//Is allowed to call any function it wants.
void bar()
{
    allowedFunction();
    disallowedFunction(); //No error
}

我想这样做的原因是因为我想确保在特定线程上调用的函数只调用实时安全函数。 由于许多应用程序需要硬实时安全线程,因此在编译时使用某种方法检测锁定将保证我们不会发生许多难以检测的运行时错误。

也许你可以把这些函数放在一个类中,并让那些允许的类的朋友像这样:

#include <iostream>

class X
{
    static void f(){}
    friend void foo(); // f() is only allowed for foo
};

void foo() // allowed
{
    X::f();
}

void bar() // disallowed
{
    //X::f();  // compile-time error
}

int main()
{

}

您可以编写一些疯狂的宏,它可以为您允许/禁止的每个功能透明地执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM