#define a template method

Viewed 87

I would like to add debug within a template function, however not looking at re-editing the whole code.

Would one be able to

    #define theFunction<T>(size) _theFunction<T>(size, __FILE__, __LINE__)
    
    template<class T>  T*  _theFunction(int size, string file, int line)
    {
        if (fails) {
            printf("theFunction failed called at line %i on %s ", line, file);
         }
     }

of course returns '<' unexpected in macro declaration. Are there some tricks to make that work?

2 Answers

Something along these lines, perhaps (not tested):

struct TheFunctionHelper {
  std::string file;
  int line;
  template<typename T> 
  T* invoke(int size) {
    return _theFunction<T>(size, file, line);
  }
};

#define theFunction TheFunctionHelper{__FILE__, __LINE__}.invoke

When writing macros it helps to use the compiler flag that lets you see the output after preprocessing. For gcc it is -E to see that this:

#define theFunction(T,size) _theFunction<T>(size, __FILE__, __LINE__)

theFunction(int,42);

Expands to:

_theFunction<int>(42, "./example.cpp", 5);

It looks a bit odd to pass int as parameter to theFunction(int,42), but once you decided to use macros, things are odd ;).

Also note that, as mentioned in a comment, C++20 has std::source_location, which eliminates one of the last corners that do require the use of macros in C++.

Related