有没有一种方法可以构建C++自定义限定符?

20

有没有办法实现自定义类型限定符(类似于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
}
我希望这样做的原因是我想确保只有实时安全函数被特定线程调用。由于许多应用程序需要硬实时安全线程,因此编译时检测锁定的某种方式将确保我们避免许多难以检测到的运行时错误。

要想向语言中添加新的关键词,没有机会(除非你能说服委员会)。你可能可以使用宏。 - Thomas Matthews
我认为你可能对这个感兴趣:元类:关于生成式 C++ 的思考 - Jesper Juhl
也许你可以将实时安全的函数声明放在特定的头文件中? - Oliv
1
这是您要找的吗?一个访问器类可能很容易解决这个问题。 - skypjack
1个回答

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

}

你可能可以编写一些疯狂的宏,为每个希望允许/禁止的函数实现透明执行。


添加好友功能并不能保证没有调用不允许的函数。因此,我们只能禁止特定的函数,而不能禁止所有函数,然后再允许几个。我需要绝对确定没有锁被占用。 - Andreas Loanjoe
@AndreasLoanjoe 如果你需要更精细的控制,我想你可能需要每个类一个函数...这就是宏更方便的地方。不过,问题很好! - vsoftco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接