带VS2010 SP1的函数模板中的编译器错误

时间:2012-02-27 14:07:21

标签: c++ c++11 visual-studio-2010 compiler-bug

为什么我会收到标记的编译器错误(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(..)使用std::back_inserter(..) - 但这不是重点。

修改

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

修改

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

4 个答案:

答案 0 :(得分:1)

您的广告有效:http://ideone.com/qAF7r

即使是古老的g ++ 4.3也可以编译它。所以它可能是MS编译器中的一个错误。

答案 1 :(得分:1)

抱歉没有VS2010可用。尝试在lambda之外移动typedef。适用于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); 
} 

答案 2 :(得分:0)

我可能误解了你想要达到的目标,但不应该仅仅是:

target.push_back(元件);

答案 3 :(得分:0)

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

target.push_back( (decltype(element))(element));