Home > Blockchain >  How to use private functions inside macros?
How to use private functions inside macros?

Time:10-05

I want to create a macro (to get line number, function name and file name) and then forward this things to another function but that function must be private but problem is that I can't use private functions inside macro.

For example suppose this C class is in my header file:

class Temp
{
    private:
    void foo(string function, string file, int line)
    {
        // Do something...
    }
    #define func() foo(__FUNCTION__,__FILE__,__LINE__)
}

Then after executing, error comes that foo is not accessible which is obvious, but is there anything I can do with this? like using Friend keyword or something else?

Purpose for doing this is that when an exception occurs (user defined) I want to print line number where exception occurred and I don't want user to use foo function that's why its private. I found out that you can use macro to pass line number to other function. Also, assume that temp class is present in my header file. And, I'm using macro func from another C file.

Any help will be appreciated.

CodePudding user response:

How to use private functions inside macros?

Exactly the same way you use them with out the macro. To call the method you need an object, you can only call it via foo within the scope of the class (it is called on this then). Also, because it is private.

This works:

#include <string>

#define func() foo(__FUNCTION__,__FILE__,__LINE__)

class Temp {
    void foo(std::string function, std::string file, int line) { }        
public:
    void foo() { 
        func();
    }
};

int main() {
   Temp{}.foo();
}

With very few exceptions, if you cannot do it without the macro, you also cannot do it with the macro. You cannot call the method like this:

int main() {
    foo("main","main.cpp",42);  // no, need object to call member function
    Temp t;
    t.foo("main","main.cpp",42); // no, method is private
}

And no macro can change this.

CodePudding user response:

The fact that you put your macro definition inside class Temp does not make it a valid method of that class. When you call it anywhere as func(); then it will expand to

 foo("some_function", "file.cpp", 1234); 

which is an error because there is no global foo() function in your code. What you want is:

Temp tmp;
tmp.foo("some_function", "file.cpp", 1234);

But it will still result in error, because foo is private, you would have to make it public.

You will also have to place Temp tmp; somewhere where it will be visible in all places where you will use your macro.

Maybe you don't need a class Temp and you can make void foo(...) a free function?

  • Related