【问题标题】:VC++ 2013 errors while using member initializer list with lambda as a memberVC++ 2013 错误,同时使用带有 lambda 作为成员的成员初始值设定项列表
【发布时间】:2016-09-05 11:16:56
【问题描述】:

我很难理解这些编译错误的根源。

以下代码在 gcc-4.9.3 和 clang-3.8 上编译没有任何问题,但在 VS 2013 上失败。

class Sample
{
    public:
        template<typename T>
        explicit Sample(T& in) : 
         x(in), 
         lamb( [](Sample& ss)
         {                                                          
           std::cout << "This works !!\n" << static_cast<const T&> (ss.get()) << std::endl;
         }){}

        const int get() const { return x; }
    private:
        int x;
        std::function<void(Sample&)> lamb;
};

int main()
{
    int z = 10;
    Sample a(z);
    return 0;
}

我最终遇到以下错误:

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2061: syntax error : identifier 'T'

MSDN 对这些错误的解释没有多大帮助。我在这里做错了什么?

【问题讨论】:

  • Compiles without any problems,确实如此。
  • 哎呀... :) :) 我用 sn-p 更新了这个问题,它确实在 gcc 和 clang 上编译得很好。 VS 2013 上仍然出错。
  • webcompiler.cloudapp.net 使用 VS,它显示了实际的错误消息,这清楚地表明 lambda 不能使用构造函数的模板参数 T(带有静态转换的行)至于是否应该,我会使用 clang 和 gcc,但这是没有理由的个人意见。
  • This 可能与我的问题类似...那么这是 VS 2013 编译器错误吗?
  • 它确实在VS2015中编译(使用error C2146: syntax error: missing '&gt;' before identifier 'T')在线static_cast

标签: c++ c++11 visual-c++ visual-studio-2013


【解决方案1】:

看起来 Visual Studio 没有将关于模板类型 T 的信息传递给 lambda。我已将类变量传递给 lambda 以收集所需的类型信息。这样的工作:

#include <functional>
#include <iostream>

class Sample
{
    public:
        template<typename T>
        explicit Sample(T& in) : 
         x(in), 
         lamb( [this](Sample& ss)
         {                                                          
           std::cout << "This works !!\n" << static_cast<decltype(x)> (ss.get()) << std::endl;
         }){}

        const int get() const { return x; }
    private:
        int x;
        std::function<void(Sample&)> lamb;
};

int main()
{
    int z = 10;
    Sample a(z);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多