我创建了一个函数声明为:
template <typename Container, typename Task>
void parallel_for_each(Container &container, Task task,
unsigned number_of_threads = std::thread::hardware_concurrency())
不难猜测它应该做什么。我想创建一个宏来简化此函数的语法并使其语法“类似循环”。我想出了一个主意:
#define in ,
#define pforeach(Z,X,Y) parallel_for_each(X,[](Z)->void{Y;})
用法为:
pforeach(double &element, vec,
{
element *= 2;
});
按预期工作,但是这个:
pforeach(double &element in vec,
{
element *= 2;
element /= 2;
});
报错
macro "pforeach" requires 3 arguments, but only 2 given
你知道如何编写一个允许甚至“更好”语法的宏吗?为什么“in”在我的代码中不代表逗号?
最佳答案
in
没有被替换的原因是它出现在类函数宏的参数中,但要替换它,这些参数必须首先传播到另一个宏:尝试
#define in ,
#define pforeach_(Z,X,Y) parallel_for_each(X,[](Z)->void{Y;})
#define pforeach(Z,X,Y) pforeach_(Z,X,Y)
注意:将in
定义为,
不会有好的结果!
添加“更好”语法的想法:
template <typename Container>
struct Helper {
Container&& c;
template <typename Arg>
void operator=(Arg&& arg) {
parallel_for_each(std::forward<Container>(c), std::forward<Arg>(arg));
}
};
#define CONCAT_(a,b) a##b
#define CONCAT(a,b) CONCAT_(a,b)
// Easier with Boost.PP
#define DEC_1 0
#define DEC_2 1
#define DEC_3 2
#define DEC_4 3
#define DEC_5 4
#define DEC_6 5
#define DEC_7 6
#define DEC_8 7
#define DEC(i) CONCAT(DEC_,i)
#define pforeach(Z, ...) \
Helper<decltype((__VA_ARGS__))> CONCAT(_unused_obj, __COUNTER__){__VA_ARGS__}; \
CONCAT(_unused_obj, DEC(__COUNTER__))=[](Z)
用作
int a[] = {1, 2, 3};
pforeach(int i, a) {
std::cout << i << ", ";
};
pforeach(int i, std::vector<int>{1, 2, 3}) {
std::cout << -i << ", ";
};
Demo .
虽然有几个缺点。我会坚持使用您目前所拥有的。
关于c++ - 定义宏改进特定函数的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29794514/