Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a class template parameter type inside a member function with a lambda fails

I have a class template with a member function that has a lambda which wants to use a class template parameter type. It fails to compile inside the lambda but succeeds, as anticipated, outside the 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;
}

The compilation error:

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

Why can't I access the class template parameter type inside the member function lambda?

What do I need to do to gain access to the class template parameter type inside the member function lambda?

like image 622
Johann Gerell Avatar asked Jun 22 '11 15:06

Johann Gerell


2 Answers

This should compile OK as-is. It appears that your compiler has a bug in the name lookup rules in a lambda. You could try adding a typedef for reporter inside report_all.

like image 113
Anthony Williams Avatar answered Oct 04 '22 22:10

Anthony Williams


Use 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);    
        });
    }
};
like image 39
Ajay Avatar answered Oct 04 '22 20:10

Ajay