【发布时间】:2017-10-25 10:49:03
【问题描述】:
(我正在使用catch 进行单元测试,不幸的是它还没有它所调用的生成器来做这种事情。)
在c++17,有没有办法减少这种情况:
assert("" == String{"" }.removeLeading(' '));
assert("a" == String{" a").removeLeading(' '));
assert("a" == String("a" }.removeLeading(' '));
assert("a" == String{"a "}.removeLeading(' '));
使用这样的宏、模板或函数:
#define MACRO(className, method, arg, ...) \
for(auto [x, y] : { __VA_ARGS }) { \
assert(x == className{y}.method(arg)); \
}
所以它更短是这样的:
MACRO(String, removeLeading, ' ',
{ "", "" }, {"a", " a"}, {"a", "a"}, {"a", "a "})
// or
MACRO(String, removeLeading, ' ',
"", "", "a", " a", "a", "a", "a", "a ")
假设所有... 参数“auto”为同一类型。
基本上对... args 的数量没有限制。 (也许可以达到 100 个?)
使用第一个 MACRO() 给出:unable to deduce 'std::initializer_list<auto>&&' from...(它也不理解语义,所以严格按照 , 标记分开,但只要正确组合,没关系。)
使用第二个MACRO() 给出:cannot decompose non-array non-class type 'const char*'
尝试模板:
template<typename T>
void TEMP(T a, T b) {
assert(a == String{ b }.removeLeading(' '));
}
template<typename T, typename... Args>
void TEMP(T a, T b, Args... args) {
TEMP(a, b);
TEMP(args...);
}
TEMP("", "", "a", " ", "a", "a", "a", "a ");
这至少有效,但我不希望将 className、method 和 arg 硬编码为 "String"、"removeLeading" 和 " "。
我想知道是否有一种方法可以使用我没有做太多的所有新类型特征/“元”模板(不知道还能如何称呼它们)来解决这个问题。 (我查看了过去一两年内可用的一些库,它们对我来说几乎就像是一种不同的语言......)
【问题讨论】:
标签: c++ templates variadic-templates c++17 variadic-macros