簡體   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