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

时间:2022-07-28 15:07:01

Is there any way to implement a custom type qualifier (similar to const)? I would like to only allow function calls to functions that are of the right qualification, within functions with the same qualification.

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

Let's say I would have:

假设我会:

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
}

The reason I would like to do this is because I want to make sure that functions called on a specific thread only call realtime-safe functions. Since many applications require hard realtime-safe threads, having some way to detect locks at compile-time would guarantee us that many hard to detect runtime errors cannot happen.

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

1 个解决方案

#1


6  

Perhaps you can put the functions in a class and make the allowed ones friends of the class like so:

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

#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()
{

}

You can probably write some crazy macro that does this transparently for every function you'd like to allow/disallow.

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

#1


6  

Perhaps you can put the functions in a class and make the allowed ones friends of the class like so:

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

#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()
{

}

You can probably write some crazy macro that does this transparently for every function you'd like to allow/disallow.

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