2016-09-23 80 views
0

为什么下面的代码不工作?宏定义为类型不起作用

// Template function definition 
template <typename T> 
void apply(const T& input); 

// Helper macro definition 
#define APPLY_FUNCTION(PIXELTYPE) \ 
    apply<##PIXELTYPE>(input); 

// Use macro to call function 
APPLY_FUNCTION(uint8_t); 

这产生以下错误:

Error: pasting "<" and "uint8_t" does not give a valid preprocessing token

+0

即使你修复了宏,你在哪里获得'输入'传递给函数? – NathanOliver

+2

宏不以分号结尾。 –

+0

不是说你错了,而是在你的宏里面有'input'似乎不是你可以选择的最佳做法。 –

回答

0

为什么您需要指定模板参数的类型呢?如果不特别希望宏然后就使用你的应用功能,直接将工作得很好:

template <class T> 
    void apply(const T & input) 
    { 
     //... 
    } 

    apply(1.0f); // Will instantiate apply<float> to match the input's type 

如果你想要的类型T是从什么传递不同的,那么我会建议以下模板而不是:

template <class T, class Input> 
    void apply(const Input & input) 
    { 
     T t(input); 
     //... 
    } 

然后可以用称为:

apply<uint8_t>(1.0f); 

而且也没有必要在这一切的宏。

8

##是用于粘贴令牌在一起。你不需要这一点,所以只是:

#define APPLY_FUNCTION(PIXELTYPE) apply<PIXELTYPE>(input); 

也就是说,两项准则:

  1. 不要结束与;要求用户宏添加它会节省你的一些错误。
  2. 请不要写这个宏。
0

在宏扩展中,##指示编译器将其前面的令牌与后面的令牌组合起来,并将结果视为单个令牌。正如错误消息所述,<uint8_t不是有效的标记。刚刚摆脱##