c++ - C++ 宏中的模板?

标签 c++ templates macros

是否可以这样做

# define abc<T1> __abc<T1, T2>

template<typename T2> void somefun() {
    ... 
    abc<int>(...);
    abc<double>(...);
    ...
}

只是为了不要每次调用 abc 时都写它

最佳答案

在 C++11 中你可以这样做:

template<typename T2> void somefun() {
    template <typename T>
    using abc = __abc<T, T2>;
}

没有它,您可以使用宏,但您需要这样做:

#define abc(T1) __abc<T1, T2>

//usage:

abc(Type) instance;

但由于这看起来不太自然,我个人会避免使用它。

如果你想避免使用 C++11 之前的宏,你可以这样做:

template <typename T2>
struct type {
  template <typename T1>
  struct lookup {
    typedef __abc<T1,T2> type;
  };
};

template <typename T2> void somefun() {
  typedef type<T2> abc;
  typename abc::template lookup<int>::type();
}

但老实说,它的可读性甚至比宏观情况还差

(注意:__abc是保留的)

关于c++ - C++ 宏中的模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10531497/

相关文章:

C++ 错误 : reference to non-static member function must be called

c++ - 如何保证 C++ 类型的位数

c++ - 使用 C++ 安装 Eclipse for scientific linux

c++ - 在 C++11 中,我可以引用在模板参数中定义的枚举类吗

c++ - 带有基类的模板类

c++ - 为什么为通用基类型编写通用代码是 C++ 中模板的糟糕替代方案?

c - 将标识符和类型传递给宏

macros - 诡计在 Racket 中的程序来源?

c++ - C++ 中的运算符重载示例

c - 检测宏的使用? (错误号)