使用lambda访问成员函数内的类模板参数类型失败

时间:2011-06-22 15:08:45

标签: c++ templates lambda c++11 traits

我有一个带有成员函数的类模板,该成员函数有一个想要使用类模板参数类型的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?

中访问类模板参数类型

如何在成员函数lambda?

中访问类模板参数类型,我需要做什么?

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分: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);    
        });
    }
};