2011-06-22 47 views
6

我有一个带有成员函数的类模板,它具有要使用类模板参数类型的lambda。它不能在lambda内进行编译,而是在lambda之外按预期成功完成。在lambda成员函数内部访问类模板参数类型失败

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

啊!我已经尝试过'typedef'ing,但是错过了关键的'''''' - 谢谢! –

+1

但不会_myreporter总是评估为'wcout_reporter'?因为'agency <>'接受默认参数,所以它是'agency '的缩写,在那个类中'_myreporter'被typedefed为wcout_reporter。或者,模板实例中的mytempalte <>实际上是否自己评估? – ted

+1

这取决于编译器。例如,VC10不捕获lambda之外的名称空间。 – Ajay

4

这应该按原样编译。看来你的编译器在lambda中的名称查找规则中有一个错误。您可以尝试在report_all内为reporter添加typedef

+0

是的,VS 2010在C++ 0x上下文中有更多的这些,例如我昨天绊倒的那个:http://stackoverflow.com/q/6432658/6345 –

相关问题