c++ 在宏中使用的模板参数有问题

栏目: C++ · 发布时间: 7年前

内容简介:http://stackoverflow.com/questions/4295890/trouble-with-template-parameters-used-in-macros

我正在尝试编译下面的代码段,我在std :: vector专门的行上收到一个错误,似乎被传入的一个参数被假定为两个参数.这是否可能与尖括号有关?

有没有一种特殊的方法/机制,通过这样的参数可以正确地传递给宏?

#include <vector>

template<typename A>
struct AClass {};

#define specialize_AClass(X)\
template<> struct AClass<X> { X a; };


specialize_AClass(int) //ok

specialize_AClass(std::vector<int,std::allocator<int> >) //error

int main()
{
   return 0;
}

我得到的错误如下:

1 Line 55: error: macro "specialize_AClass" passed 2 arguments, but takes just 1
2 Line 15: error: expected constructor, destructor, or type conversion before 'int'
3 compilation terminated due to -Wfatal-errors.

链接: http://codepad.org/qIiKsw4l

你有两个选择.其中一个已经提到了:使用__VA_ARGS__.然而,这具有在严格C 03中不起作用的缺点,但是需要足够的C99 / C 0x兼容的预处理器.

另一个选项是括号化类型名称.但是不像另一个答案所说,它并不像括号化类型名称那么容易.如下撰写专业化形式不明

// error, NOT valid!
template<> struct AClass<(int)> { X a; };

我已经解决了这个问题(并且boost可能在引擎盖下使用相同的方式),通过将类型名称传递给括号,然后从其中构建一个函数类型

template<typename T> struct get_first_param;
template<typename R, typename P1> struct get_first_param<R(P1)> {
  typedef P1 type;
};

因此,get_first_param<void(X)> :: type表示类型X.现在可以将宏重写为

#define specialize_AClass(X) \
template<> struct AClass<get_first_param<void X>::type> { 
  get_first_param<void X>::type a; 
};

而你只需要传递包含在括号中的类型.

http://stackoverflow.com/questions/4295890/trouble-with-template-parameters-used-in-macros


以上所述就是小编给大家介绍的《c++ 在宏中使用的模板参数有问题》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

500 Lines or Less

500 Lines or Less

Amy Brown、Michael DiBernardo / 2016-6-28 / USD 35.00

This book provides you with the chance to study how 26 experienced programmers think when they are building something new. The programs you will read about in this book were all written from scratch t......一起来看看 《500 Lines or Less》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

html转js在线工具
html转js在线工具

html转js在线工具