C++ Trick:宏函数与模板类之殇
![作者头像](https://ask.qcloudimg.com/http-save/yehe-1413472/ca38c0904d50101a4ca548e72e6f2227.jpeg)
这是一个小trick。虽然不难理解,但是可能经常会忘记,导致代码返工。看这段代码:
#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;
#define DECLARE(type, var) type var
int main() {
DECLARE(vector<string>, vs);
DECLARE(map<string, int>, msi);
return 0;
}
g++和clang都会编译报错。g++错误信息如下:
map_m.cpp:13:34: 错误:宏“DECLARE”传递了 3 个参数,但只需要 2 个
DECLARE(map<string, int>, msi);
map_m.cpp: 在函数‘int main()’中:
map_m.cpp:13:5: 错误:‘DECLARE’在此作用域中尚未声明