英文:
Parameter corresponding to function call with braced literal list
问题
As per a comment on https://stackoverflow.com/questions/76554088/iterating-over-a-short-fixed-list-of-strings it turns out that in modern C++ you can write:
在 https://stackoverflow.com/questions/76554088/iterating-over-a-short-fixed-list-of-strings 上的一条评论表明,在现代 C++ 中,你可以这样写:
for (auto color: {"red", "green", "blue"})
你可以使用类似的方法来调用函数吗?如果可以,相应的参数声明语法是什么?换句话说,
void foo( /* ... */ )
foo({"red", "green", "blue"});
对于 ...
应该替换为什么?
英文:
As per a comment on https://stackoverflow.com/questions/76554088/iterating-over-a-short-fixed-list-of-strings it turns out that in modern C++ you can write:
for (auto color: {"red", "green", "blue"})
Can you do something similar with a function call, and if so, what is the corresponding parameter declaration syntax? In other words,
void foo( /* ... */ )
foo({"red", "green", "blue"});
What should be substituted for the ...
?
答案1
得分: 4
这是一个使用参数包和折叠表达式的替代方法:
#include <iostream>
#include <utility>
template <class... Args>
void foo(Args&&... args) {
(..., (std::cout << std::forward<Args>(args) << ' '));
}
int main() {
foo("红色", "绿色", "蓝色");
}
英文:
Here's an alternative with a parameter pack and a fold expression:
#include <iostream>
#include <utility>
template <class... Args>
void foo(Args&&...args) {
(..., (std::cout << std::forward<Args>(args) << ' '));
}
int main() {
foo("red", "green", "blue");
}
答案2
得分: 2
你也可以使用函数模板来实现它:
#include <string_view>
#include <iostream>
template<std::size_t N>
void foo(const std::string_view(&strings)[N])
{
for (const auto string : strings)
{
std::cout << string << "\n";
}
}
int main()
{
foo({ "red","green","blue" });
return 0;
}
英文:
You can also do it with a function template :
#include <string_view>
#include <iostream>
template<std::size_t N>
void foo(const std::string_view(&strings)[N])
{
for (const auto string : strings)
{
std::cout << string << "\n";
}
}
int main()
{
foo({ "red","green","blue" });
return 0;
}
答案3
得分: 1
Yes, you can. 通常的方式是将 foo
声明为接受一个 initializer_list
的函数,例如:
#include <iostream>
#include <string>
#include <initializer_list>
void foo(std::initializer_list<std::string> il)
{
for (const auto &s : il)
std::cout << s << " ";
}
int main()
{
foo({"red", "green", "blue"});
}
请注意,例如 std::vector
就有这样的构造函数,列表中的所有对象必须是相同类型。
英文:
Yes you can. The usual way is to declare foo
as taking an initializer_list
, e.g.:
#include <iostream>
#include <string>
#include <initializer_list>
void foo (std::initializer_list <std::string> il)
{
for (const auto &s : il)
std::cout << s << " ";
}
int main()
{
foo ({"red", "green", "blue"});
}
Note that, for example, std::vector
has just such a constructor and that all objects in the list must be of the same type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论