【问题标题】:Is there a way to build C++ custom qualifiers?有没有办法构建 C++ 自定义限定符?
【发布时间】:2018-01-07 05:28:04
【问题描述】:

有没有办法实现自定义类型限定符(类似于 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
}

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

【问题讨论】:

  • 给语言添加新的关键字,没有没有机会(除非你能说服委员会)。您也许可以使用宏。
  • 我想你可能对此感兴趣:Metaclasses: Thoughts on generative C++
  • 也许你可以把实时安全的函数声明放在特定的头文件中?
  • this 你在找什么?访问器类可能很容易解决问题。

标签: c++ compile-time qualifiers


【解决方案1】:

也许您可以将函数放在一个类中,并像这样让允许的人成为该类的朋友:

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

}

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

【讨论】:

  • Friending 函数并不能保证我不会调用不允许的函数。这样我们只能禁止特定功能,而不是禁止所有功能然后允许多个功能。我需要绝对确定没有被锁。
  • @AndreasLoanjoe 为了获得更好的控制,我猜每个类都需要一个函数......这就是宏变得更方便的地方。不过问题很好!
猜你喜欢
  • 2019-11-28
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2019-08-22
  • 1970-01-01
  • 2020-12-27
  • 2021-12-16
  • 1970-01-01
相关资源
最近更新 更多