2017-07-31 115 views
18

是否有任何方法来实现自定义类型限定符(类似于const)?我想只允许对具有相同资格的函数进行函数调用,以获得正确的资格。有没有办法构建C++自定义限定符?

比方说,我将有:

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 
} 

我想这样做的原因是因为我想确保函数调用上的特定线程只能调用实时的安全保护功能。由于许多应用程序都需要硬实时安全线程,因此在编译时有一些检测锁的方式可以保证我们很难检测到运行时错误。

+0

要为该语言添加新关键字,请不要有机会(除非您能说服委员会)。您可能可以使用宏。 –

+0

我想你可能会对此感兴趣:[Metaclasses:关于生成C++的思考](https://herbsutter.com/2017/07/26/metaclasses-thoughts-on-generative-c/) –

+0

也许你可以把特定头文件中的实时安全函数声明? – Oliv

回答

6

也许你可以把功能的一类,使类的允许那些朋友,像这样:

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

} 

你或许可以写一些疯狂的宏,透明地做到这一点每一个你想要的功能允许/禁止。

+0

但是,Friending函数并不能保证我不会调用不允许的函数。这样我们只能禁止特定的功能,不允许禁止所有功能,然后允许多个功能。我需要绝对确保不会发生锁定。 –

+0

@AndreasLoanjoe为了更好的控制,你需要每个类的一个函数,我猜...这就是宏变得更加容易的地方。不错的问题,但! – vsoftco

相关问题