我有点不确定新的(从 c++11 开始)基于范围的循环内部是如何工作的。
如果我要做类似的事情...
for( auto i : someclass.Elements() )
{
...
}
Run Code Online (Sandbox Code Playgroud)
...其中“Elements()”返回临时值,是否有任何我可能不知道的副作用?
我将在这个问题的底部添加一个工作原型。
我已经验证“Elements()”返回的类型被创建一次,这是我最关心的。说实话,这感觉有点太简单了,而且我还没有在其他地方看到过这种实现。
对于上下文,我创建了一个 XML 库,并且希望能够迭代元素的子元素 ("for( auto child: element->Children() ) {...}"),它的属性 ("for( auto attribute : element->Attributes() ( {...}"),也许还有更具体的子元素 ("for( auto cats : element->Children( "cats" ) ) {...}"。
这是一个工作原型:
#include <iostream>
#include <list>
#include <vector>
#include <string>
template< typename T >
class Array
{
public:
Array()
{
}
Array( T firstValue )
{
m_elements.push_back( firstValue );
}
Array( const std::list< T > & values ) …
Run Code Online (Sandbox Code Playgroud) 本着通用编程的精神,我创建了以下代码:
#include <iostream>
#include <functional>
class Functor
{
public:
void operator()()
{
std::cout << "Functor operator called." << std::endl;
}
};
void Function()
{
std::cout << "Function called." << std::endl;
}
void Call( auto & fp )
{
static int i;
std::cout << "Unified calling..." << &i << std::endl;
fp();
}
int main( int argc, char ** argv )
{
Functor functor;
std::function< void() > function = Function;
std::cout << "Begin testing..." << std::endl;
Call( functor );
Call( function ); …
Run Code Online (Sandbox Code Playgroud)