Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to build C++ custom qualifiers?

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.

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.

like image 660
Andreas Loanjoe Avatar asked Jul 31 '17 15:07

Andreas Loanjoe


1 Answers

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.

like image 74
vsoftco Avatar answered Nov 20 '22 12:11

vsoftco