Accessing a class template parameter type inside a

2019-06-19 01:23发布

问题:

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?

回答1:

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);    
        });
    }
};


回答2:

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.