c++中的模板代码块
Template code blocks in C++?
最近我在做一个项目,它需要很多像"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"
十次。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值