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

流过昼夜 提交于 2019-12-23 09:16:30

问题


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.



来源:https://stackoverflow.com/questions/6442129/accessing-a-class-template-parameter-type-inside-a-member-function-with-a-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!