c++ - #定义一个模板方法

标签 c++ templates

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

可以吗

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

当然会在宏声明中返回意外的“<”。有一些技巧可以实现这一点吗?

最佳答案

也许是这样的(未测试):

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

关于c++ - #定义一个模板方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65291188/

相关文章:

c++ - 从图像中获取不正确的读数

c++ - 为什么在推导模板参数时应用 §5/5?规则不能不同吗?

php - Page.php 不显示 wordpress 中的更改

c++ - final 用于 C++ 中的优化吗?

c++ - 在函数的整个生命周期内都有一个对象在堆栈上

c++ - 无法在我的 exe 文件的动态库中找到项目入口点

C++1y 没有从 std::bind 到 std::function 的可行转换

c++ - "Invalid use of incomplete type"使用模板化类型和命名空间

javascript - 仅当给定 Handlebar 变量时才显示周围的 HTML

c++了解模板,类型名称的语法