【问题标题】:Accessing a class template parameter type inside a member function with a lambda fails使用 lambda 访问成员函数内的类模板参数类型失败
【发布时间】:2011-06-23 00:02:00
【问题描述】:

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

【问题讨论】:

  • 在 GCC 4.6 上为我编译。你的平台/编译器是什么?

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


【解决方案1】:

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

【讨论】:

【解决方案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);    
        });
    }
};

【讨论】:

  • 啊!我已经尝试过typedefing,但错过了关键的agency&lt;&gt; - 谢谢!
  • 但是 _myreporter 不会总是评估为 wcout_reporter 吗?因为agency&lt;&gt; 接受默认参数,所以它是agency&lt;wcout_reporter&gt; 的简写,并且在该类中_myreporter 的类型定义为wcout_reporter。或者模板实例中的 mytempalte 是否实际上对自身进行评估?
  • 这取决于编译器。例如,VC10 不会捕获 lambda 之外的命名空间。
猜你喜欢
  • 2015-04-20
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-06
相关资源
最近更新 更多