Search code examples
c++functionmacrosbracketsstatements

Allowing certain function call only if it is followed by another function


I want to create a function that must be called with { } braces. Similar to if, while and for statements. The reason for this is to prevent the operator from calling the function without adding the necessary code that follows.

#include <iostream>

/* function to run the test */
bool runTest()
{
    std::cout "PASS" << std::endl;
    return true;
}

/* function will print the passed chars */
void newTest(const char *functionName, const char *testName)
{
    std::cout << functionName << " " << testName;
}

int main(void)
{
    /* OPTION 1 */
    /* You can call it like this */
    newTest("runTest", "TestName");
        runTest();
    / * OR */
    newTest("runTest", "TestName");
    {
        runTest();
    }

    /* OPTION 2 */
    /* I want the operator to be required to do */
    newTest("runTest", "TestName")
    {
        runTest();
    }
    return 0;
}

I want option 2 to be the correct usage. Because with option 1 you could call that like:

newTest("runTest", "TestName");
newTest("otherTest", "TestName");
   runTest();

but you would not have the necessary call to runTest() that is related to the first calls output.

The output would be:

runTests TestName /*(NULL)*/
otherTest TestName PASS

This way of calling is just checking to make sure the operator called the test after the newTest() function.

Ideally if the operator was perfect he could call the functions properly.

newTest("runTest", "TestName");
    runTest();
newTest("otherTest", "TestName");
   runTest();

But i want to eliminate the error but automatically requiring the operator to call the function with {} following the call.


Solution

  • Firstly, those 'curly brackets' are called 'braces' - you may want to edit your question so people understand better.

    unless someone changed it without telling me; C++ doesn't work this way. Braces in this context are reserved explicitly for the scope of keywords, function-definitions, and initializer lists.

    void Badger()
    { //this is fine, it's a function-definition
    }
    int main()
    {
    for(I =0; I < 5; I++)
       { //this is fine, for is a keyword.
       }
    foo()
       { //This is not legal, foo must take it's perimeters within brackets, not braces.
       } 
    }
    

    If you wish a user to pass code to a function, you must do so using a Function-pointer, the user then may pass a existing function, or a lambda.

    void Foo(bool (Function_ptr*) ()) { };
    bool Function_To_Pass() { } ;
    int main()
    {
        Foo(&Function_To_Pass);
        Foo([]()
        {
            //Code to run here
        });
    }