简体   繁体   中英

Is it possible to detect if a function is called at compile time

I'm developing a C++ library, there are two functions: func1 and func2 .

I want to generate an compile-time error if developer forgets to call func1 before calling func2 :

This will be OK:

func1();
func2();  // OK

But this would fail:

func2();  // ERROR, you forget to call func1()

Of course, it's very easy to generate a runtime error but I would like to generate a compile-time error.

I've tried as below but it's not working because I can't modify a constexpr variable:

static constexpr bool b {false};

void func1() {
    b = true; // ERROR!
}

typename<std::enable_if_t<b == true>* = nullptr>
void func2() {}

I'm not very good at metaprogramming. I want to know if it's possible to generate a compile-time error in this case.

It is not possible at least in corner cases. Look at the following code (headers and test for scanf return value omitted for brievety):

int main() {
    int code;
    printf("Enter code value: ");
    scanf("%d", &code);
    if (code > 0) func1();
    func2();               // has func1 be called ?
    return 0;
}

Here, even the best static analysis tool will be unable to state whether func1 is called before func2 because it depends on a value which will only be known at runtime. Ok, this is a rather stupid example, but real world programs often read their config data at run time and that config can change even part of their initialization.

Make temporal coupling explicit:

  • make func1 return a type which should be consumed by func2 :
struct func1_result {
// Possibly constructors private, and friendship to `func1`.
//...
};

func1_result func1();
void func2(const func1_result&);

So you cannot call func2 without creating first func1_result (returned by func1 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM