访问具有lambda的成员函数内部的类模板参数类型失败

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

本文关键字:参数 失败 类型 函数 lambda 成员 访问 内部      更新时间:2023-10-16

我有一个类模板,它有一个成员函数,该函数有一个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中的类模板参数类型?

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

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