2011-09-16 40 views
3

不知道什麼我試圖做的是不好的,但這裏是我的問題: 我有一些模板的功能,如對模板的宏

std::vector<T> operator - (const std::vector<T>& data1, const std::vector<T>& data2); 
std::vector<T> operator * (const std::vector<T>& data1, const std::vector<T>& data2); 
std::vector<T> operator & (const std::vector<T>& data1, const std::vector<T>& data2); 

....等等。所有這些功能都完全一樣的定義,除了運營商,所以我試圖寫這樣

#define _BINARY_OP_ON_DATASET (OP_TYPE) 
    template <typename T> \ 
    std::vector<T> operator OP_TYPE (const std::vector<T>& data1, const std::vector<T>& data2)\ 
    {\ 
    std::vector<T> result;\ 
    result.push_back(data1.begin().val OP_TYPE data1.begin().val)/*sample implementation*/\ 
    return result;\ 
    } 

_BINARY_OP_ON_DATASET (&) 
_BINARY_OP_ON_DATASET (+) 

一個宏,我得到了一堆錯誤

Error 1 error C2833: 'operator OP_TYPE' is not a recognized operator or type 
Error 2 error C2988: unrecognizable template declaration/definition 
Error 3 error C2059: syntax error : 'newline' 
Error 5 error C2143: syntax error : missing ';' before '<' 
Error 6 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 

...以及更多 任何人都可以看到這是什麼問題?

感謝您的任何幫助。

CV

+0

你打算怎麼到包含''T' +'雙載體?你怎麼去'&'和'--'兩個向量? – Nawaz

+0

我的壞..這是一個錯字,編輯的代碼 – blueskin

+0

確定..爲Kerrek SB和ildjarn指出,他們是愚蠢的語法錯誤。 – blueskin

回答

2

宏觀參數列表之前沒有足夠的空間!

#define _BINARY_OP_ON_DATASET(OP_TYPE) ... 
          ^^^ 
+2

並在最後加一個反斜線以換出換行符,對不對? – ildjarn

+0

ahhh,該死的..這種愚蠢的錯誤..我討厭我自己 – blueskin

+0

@ildjarn:啊,是的,第一個換行沒有轉過頭。接得好。 –

0

我想重複定義會比宏觀fying他們:)簡單有時,它只是更好地重複自己,而不是伊克更多的打字效率。

+0

在一些非常簡單的情況下,也許,但是您可能需要重複的代碼很大。重複定義意味着如果你在一箇中改變了某些東西,你必須在它們中改變它,這可能導致可能的不一致。 – Shahbaz

+0

我同意........ – blueskin

+0

啊,我試過了哈哈。希望我們可以做到沒有downvotes雖然:\ –

2

您有宏參數列表之前的無效空間而錯過逃脫換行符後:

#define _BINARY_OP_ON_DATASET(OP_TYPE) \ 
    ... 
3

刪除宏的名稱之間的空間和它的參數。

#define _BINARY_OP_ON_DATASET(OP_TYPE) 

添加\到您的模板的第一行

#define _BINARY_OP_ON_DATASET(OP_TYPE)\ 

取出小錯誤,比如你在你的函數體的第二行忘了;

result.push_back(data1.begin().val+data1.begin().val); 

而且它編譯得很好!

+0

謝謝shahbaz .. – blueskin