2016-09-23 76 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不是有效的標記。剛剛擺脫##