Home > Blockchain >  Replace C class/static method with preprocessor?
Replace C class/static method with preprocessor?

Time:10-22

I'd like to use the built-in compiler checks to verify format strings of a custom logging framework to catch the odd runtime crash due to mismatching format string <-> parameters in advance.

Arguments of the custom C logging methods are identical to the printf() family so I was attempting to replace all calls to

MyLogger::Error(

with

fprintf(stderr,

Though unfortunately the (clang) preprocessor chokes on the scope resolution operator (::), i.e. instead of ULog::Warn( only the ULog substring is recognized:

#define MyLogger::Error( fprintf(stderr,

Any suggestions on how to make this work much appreciated.

CodePudding user response:

Have you tried a variadic template? found here.

#include <iostream>

namespace MyLogger
{
    template <typename... T> 
    auto Error(const char * _Format, T &&... args) 
    { 
        return printf(_Format, std::forward<T>(args)...); 
    };
}

#define printf(...) MyLogger::Error(__VA_ARGS__)

int main() 
{
    MyLogger::Error("Non-Macro Print \n");
    printf("Macro Print \n");

    return 0;
}

CodePudding user response:

What if you modify MyLogger::Error to

MyLogger::Error(args){
    if (0) {
        fprintf(stderr,args)
    }
    //actual function
}

This way you get the built-in warnings and it does not effect the efficiency of your code. (You can obviosly actually use the print if you wan to write to stderr, but I think if you wanted that you used that already)

  • Related