c++中的模板代码块

Template code blocks in C++?

本文关键字:代码 c++      更新时间:2023-10-16

最近我在做一个项目,它需要很多像"repeat"answers"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++版本中实现类似的东西的变通方法吗?

在未来的c++版本中是否有机会添加这样的特性?

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...
}

同时,提振。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++ 11) std::function对象,std::bind表达式或lambda表达式)。

那么你的repeat函数可以是这样的:

template<typename Tpred>
void repeat(unsigned count, Tpred predicate)
{
    while (count--)
        predicate();
}

上面的函数可以用作

repeat(10, [](){ std::cout << "hellon"; });

上面的调用将导致lambda被调用十次,因此它将打印"hello"十次。