我希望编写一个函数,可以接受可变数量的字符串字面值参数。如果我使用C语言编写,可能需要编写类似以下的代码:
void foo(const char *first, ...);
然后调用将会是这个样子:
foo( "hello", "world", (const char*)NULL );
感觉 C++ 应该可以做得更好。我想到的最好的方法是:
template <typename... Args>
void foo(const char* first, Args... args) {
foo(first);
foo(args);
}
void foo(const char* first) { /* Do actual work */ }
称为:
foo("hello", "world");
但我担心递归性质和我们在只有一个参数时才进行任何类型检查的事实,会使得如果某人调用foo("bad", "argument", "next", 42)
将导致错误难以理解。我想要写的是:
void foo(const char* args...) {
for (const char* arg : args) {
// Real work
}
}
有什么建议吗?
编辑:还有一个选项是void fn(std::initializer_list<const char *> args)
,但这会使调用变成foo({"hello", "world"});
,而我想避免这种情况。
foo("hello", "world");
所束缚?如果不是,那么std::initializer_list<const char *>
就是一个合适的参数类型。 - CalethT args...
意味着从所有剩余参数初始化的“std::initializer_list<T>
”,那么不行。 - Martin Bonner supports Monica