gpt4 book ai didi

c++ - C++ 中的模板代码块?

转载 作者:行者123 更新时间:2023-11-30 01:58:46 25 4
gpt4 key购买 nike

最近我在做一个项目,它需要很多结构,比如“repeat”和“foreach”。我知道 C++ 中没有这样的结构,但我试着想象它们可能是什么样子。

repeat(count)
{
...
}

foreach(someList, it)
{
...
}

由于 C++ 已经支持模板内联函数,因此也支持模板代码块需要很少的更改。一种可能的语法可能是这样的:

template<unsigned count> repeat(unsigned count)
while(count--) __code;

template <class ContainerT, typename ContainerT::iterator it>
foreach(ContainerT& cn, typename ContainerT::iterator it)
for(typename ContainerT::iterator it=cn.begin(); it!=cn.end(); ++it) __code;

您如何看待这种语法?是否有机会在未来的 C++ 版本中添加此类功能?您知道在当前 C++ 版本中实现类似功能的任何解决方法吗?

最佳答案

Is there any chance for such feature to be added in future C++ versions?

C++11 具有基于范围的 for 循环:

for (auto elem : cont) // (perhaps use auto&, auto const&, or auto&&,
// depending on your use case)
{
// Do what you want with elem...
}

或者,您可以将 std::for_each() 与 lambda 一起使用:

std::for_each(cont.begin(), cont.end(), 
[&] (decltype(cont)::value_type const& elem)
// ^^^^^^
// Or whatever fits your needs
{
// Do what you want with elem...
}

此外,Boost.Range具有允许处理范围而不是迭代器对的 C++ 标准算法版本:

#include <boost/range/algorithm.hpp>

// ...

std::vector<int> v = { 1, 2, 3 };
boost::for_each(v, [] (int i) { std::cout << i * 2 << std::endl; });

关于c++ - C++ 中的模板代码块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16883265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com