20

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.

Andreas Loanjoe
  • 2,205
  • 10
  • 26
  • To add new keywords to the language, no there is no chance (unless you can persuade the Committee). You may be able to use macros. – Thomas Matthews Jul 31 '17 at 15:04
  • I think you may be interrested in this: [Metaclasses: Thoughts on generative C++](https://herbsutter.com/2017/07/26/metaclasses-thoughts-on-generative-c/) – Jesper Juhl Jul 31 '17 at 15:05
  • Maybe you could just put realtime-safe function declaration in specific header files? – Oliv Jul 31 '17 at 16:35
  • 1
    Is [this](https://wandbox.org/permlink/KPAy02Xi11GFsR4P) what you are looking for? An accessor class can easily solve the problem probably. – skypjack Jul 31 '17 at 19:24

1 Answers1

6

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.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • Friending functions doesn't however guarantee me that no disallowed functions are called. In this way we can only disallow specific functions, not disallow all functions and then allow several. I need to be absolutely sure that no locks are taken. – Andreas Loanjoe Jul 31 '17 at 15:10
  • @AndreasLoanjoe For finer control you'd need one function per class I guess... That's where a macro comes handier. Nice question though! – vsoftco Jul 31 '17 at 15:12