3

为什么我得到标记的编译器错误(C2899)?我尝试使用 VS2010 SP1。

#include <list>
#include <vector>
#include <algorithm>

template <typename source_container_type, typename target_container_type>
void copy_all(const source_container_type& source, target_container_type& target)
 {
    std::for_each(begin(source), end(source), [&] (const typename source_container_type::value_type& element)
    {
        // error C2899: typename cannot be used outside a template declaration
        // error C2653: 'target_container_type' : is not a class or namespace name
         target.push_back(typename target_container_type::value_type(element));
    });
}

int main()
{
    std::vector<int> a;
    a.push_back(23);
    a.push_back(24);
    a.push_back(25);

    std::list<int> b;
    copy_all(a, b);
}

亲切的问候
西蒙

PS:我知道我可以使用std::copy(..)with std::back_inserter(..)- 但这不是重点。

编辑

perreal 在评论中回答了这个问题: http ://connect.microsoft.com/VisualStudio/feedback/details/694857/bug-in-lambda-expressions

编辑

请注意,我对解决方法不感兴趣。我想知道上面的代码是否应该编译。

4

4 回答 4

1

您的线路有效:http: //ideone.com/qAF7r

甚至古老的 g++ 4.3 也编译它。因此,这可能是您的 MS 编译器中的错误。

于 2012-02-27T14:21:11.107 回答
1

抱歉,没有可用的 VS2010。尝试将 typedef 移到 lambda 之外。适用于 g++。

#include <list> 
#include <vector> 
#include <algorithm> 

template <typename source_container_type, typename target_container_type> 
void copy_all(const source_container_type& source, target_container_type& target) 
 {
    typedef typename target_container_type::value_type TargetType; /// Code change here.

    std::for_each(source.begin(), source.end(), [&] (const typename source_container_type::value_type& element) 
    { 
         target.push_back(TargetType(element)); 
    }); 
} 

int main() 
{ 
    std::vector<int> a; 
    a.push_back(23); 
    a.push_back(24); 
    a.push_back(25); 

    std::list<int> b; 
    copy_all(a, b); 
} 
于 2012-02-27T14:44:14.617 回答
0

我可能误解了您要达到的目标,但有问题的行不应该只是:

目标.push_back(元素);

于 2012-02-27T14:17:09.947 回答
0

由于您使用的是 C++0x/11,因此您可以使用:

target.push_back( (decltype(element))(element)); 
于 2012-02-27T14:24:02.027 回答