2009-06-15 56 views
0

我已經有了一些代碼,我想在地圖中使用映射的值來構建元素的向量。下面的代碼在Visual Studio中工作正常(就我所知,似乎是合法的),但是g ++不同意。g ++中的模板函數錯誤

template<class PAIR> 
typename PAIR::second_type foo(const PAIR& arg) 
{ 
    return (arg.second); 
} 

class A 
{ 
private: 
    typedef std::map<int, std::wstring> map_t; 
    map_t m_map; 

public: 
    void bar() 
    { 
     // Attempt to pulled the mapped type from the map into the vector 
     std::vector<std::wstring>vect(m_map.size()); 
     std::transform(m_map.begin(), m_map.end(), vect.begin(), 
      &foo<map_t::value_type>); // <-- error here, see below, also 

     // other attempts that all failed: 
     // - std::transform(..., boost::bind(foo<map_t::value_type>, _1)); 
     // - std::transform(..., boost::bind(&map_t::value_type::second, _1)); 
     // - also tried casting foo to a specific function type 
     // - also tried "template<class T> T itself(T arg) { return T; }" applied to all the above functor candidates, a la "std::transform(..., itself(<<functor>>));" 
    } 
}; 

不幸的是,我沒有確切的錯誤文本與我(的東西有關無法找出哪個重載函數使用)的時刻或g的特定版本++(最近一次是與分佈式Ubuntu),但是當我得到這些信息時我會更新這篇文章。

同時,任何人都可以解釋爲什麼g ++無法解析正在提供的仿函數的類型嗎?

+0

編譯對我來說沒有任何問題(G ++ 4.3.3-5ubuntu4)。即使 - 牆壁也不會給出任何警告。 – sth 2009-06-15 16:57:42

回答

1

我的機器上編譯如下:

#include <map> 
#include <vector> 
#include <algorithm> 
#include <string> 

template<class PAIR> 
typename PAIR::second_type foo(const PAIR& arg) 
{ 
    return (arg.second); 
} 

class A 
{ 
private: 
    typedef std::map<int, std::wstring> map_t; 
    map_t m_map; 

public: 
    void bar() 
    { 
     std::vector<std::wstring>vect(m_map.size()); 
     std::transform(m_map.begin(), m_map.end(), vect.begin(), 
      &foo<map_t::value_type>); 
    } 
}; 

命令行:

g++ -c overt.cpp 

版本:

$ g++ --version 
i686-apple-darwin9-g++-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5490) 
Copyright (C) 2005 Free Software Foundation, Inc. 
This is free software; see the source for copying conditions. There is NO 
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.