2011-06-22 9 views
6

クラステンプレートパラメータ型を使用するラムダを持つメンバ関数を持つクラステンプレートがあります。それはラムダの内部ではコンパイルに失敗しますが、ラムダの外側では予期どおり成功します。ラムダを持つメンバ関数内のクラステンプレートパラメータ型にアクセスできません

struct wcout_reporter 
{ 
    static void report(const std::wstring& output) 
    { 
     std::wcout << output << std::endl; 
    } 
}; 

template <typename reporter = wcout_reporter> 
class agency 
{ 
public: 

    void report_all() 
    { 
     reporter::report(L"dummy"); // Compiles. 

     std::for_each(reports_.begin(), reports_.end(), [this](const std::wstring& r) 
     { 
      reporter::report(r); // Fails to compile. 
     }); 
    } 

private: 

    std::vector<std::wstring> reports_; 
}; 

int wmain(int /*argc*/, wchar_t* /*argv*/[]) 
{ 
    agency<>().report_all(); 

    return 0; 
} 

コンパイルエラー:

error C2653: 'reporter' : is not a class or namespace name 

私はメンバ関数ラムダ内でクラステンプレートのパラメータの型にアクセスできないのはなぜ?

メンバー関数lambda内のクラステンプレートパラメータ型にアクセスするには、何が必要ですか?

+3

はGCC 4.6で私のためにコンパイルします。あなたのプラットフォーム/コンパイラは何ですか? –

+0

@Kerrek:Visual C++ 2010. –

答えて

2

使用のtypedef:

template <typename reporter = wcout_reporter> 
class agency 
{ 
    typedef reporter _myreporter; 
public: 
    void report_all()  
    {   
     reporter::report(L"dummy"); // Compiles.   

     std::for_each(reports_.begin(), reports_.end(), [this](const std::wstring& r)   
     { 
      // Take it 
      agency<>::_myreporter::report(r);  
     }); 
    } 
}; 
+0

Ah !私はすでに 'typedef'を試していましたが、重要な'代理店 ' - 逃しました - ありがとう! –

+1

しかし、_myreporterは常に 'wcout_reporter'と評価されませんか? 'agency <>'はデフォルトのパラメータを受け入れるので、 'agency 'の省略形であり、 '_myreporter'クラスはwcout_reporterとして型定義されています。または、テンプレートのインスタンス内のmytempalte <>は実際に自分自身に評価されますか? – ted

+1

これはコンパイラによって異なります。 VC10は、例えばラムダの外側の名前空間を取得しません。 – Ajay

4

これは現状どおりにコンパイルする必要があります。あなたのコンパイラはラムダ内の名前検索規則にバグを持っているようです。 reportertypedefreport_allに追加してみてください。

+0

はい、VS 2010には、C++ 0xの文脈でこれらの多くがあります。たとえば、私は昨日上がったものです:http://stackoverflow.com/q/6432658/6345 –

関連する問題