小编Kit*_*t10的帖子

来自成员函数返回的临时值的基于范围的循环

我有点不确定新的(从 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)

c++ c++11

4
推荐指数
1
解决办法
3064
查看次数

使用auto作为参数会有负面影响吗?

本着通用编程的精神,我创建了以下代码:

#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)

c++ templates auto c++14

3
推荐指数
1
解决办法
93
查看次数

标签 统计

c++ ×2

auto ×1

c++11 ×1

c++14 ×1

templates ×1