gpt4 book ai didi

c++ - 手工自动模板(不使用C++0x)

转载 作者:可可西里 更新时间:2023-11-01 17:01:11 27 4
gpt4 key购买 nike

如何在不使用c++0x标准的情况下实现auto关键字功能?

for(std::deque<std::pair<int, int> >::iterator it = points.begin();
it != points.end(); ++it)
{
...
}

也许这样的类:

class AUTO
{
public:
template <typename T1>
AUTO(T1);

template <typename T2>
operator T2();
};

这样的用法:

for(AUTO it = points.begin(); it != points.end(); ++it)
{
...
}

但是,T1 和 T2 是不同的。如何将有关 T1 的信息移动到 operator T2()?真的可以吗?

最佳答案

如果库扩展很容易实现,就不需要语言扩展了。参见 N1607有关自动提案的详细信息。

然而,articleBoost.Foreach 上(哪一种做你想做的)宏可能有助于理解与此类实现相关的问题。

What is BOOST_FOREACH?

In C++, writing a loop that iterates over a sequence is tedious. We can either use iterators, which requires a considerable amount of boiler-plate, or we can use the std::for_each() algorithm and move our loop body into a predicate, which requires no less boiler-plate and forces us to move our logic far from where it will be used. In contrast, some other languages, like Perl, provide a dedicated "foreach" construct that automates this process. BOOST_FOREACH is just such a construct for C++. It iterates over sequences for us, freeing us from having to deal directly with iterators or write predicates.

BOOST_FOREACH is designed for ease-of-use and efficiency. It does no dynamic allocations, makes no virtual function calls or calls through function pointers, and makes no calls that are not transparent to the compiler's optimizer. This results in near-optimal code generation; the performance of BOOST_FOREACH is usually within a few percent of the equivalent hand-coded loop. And although BOOST_FOREACH is a macro, it is a remarkably well-behaved one. It evaluates its arguments exactly once, leading to no nasty surprises.

关于c++ - 手工自动模板(不使用C++0x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3647462/

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