提问者:小点点

#定义模板方法


我想在一个模板函数中添加debug,但是不考虑重新编辑整个代码。

一个人能不能

    #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);
         }
     }

当然返回'<'宏声明中意外。有什么窍门能让它奏效吗?


共2个答案

匿名用户

也许(没有经过测试):

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

匿名用户

在编写宏时,使用编译器标志有助于您查看预处理后的输出。对于gcc,可以使用-e:

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

theFunction(int,42);

扩展到:

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

int作为参数传递给thefunction(int,42)看起来有点奇怪,但是一旦您决定使用宏,事情就很奇怪了。)。

还要注意,正如在注释中提到的,C++20具有std::source_location,这消除了C++中需要使用宏的最后一个角落。