非静态成员的λ类不能使用默认模板paramers?(Class with non-static la

2019-09-23 06:24发布

这个小测试程序:

#include <functional>

//template<class T>            // <-- with this, gcc compiles  ok
template<class T=void>
struct  c{
        std::function<int(int)> f = [](int i){return i+i;};
};

int main() {};

锵-3.2编译就OK了,但是从GCC 4.7.1和4.8我得到奇怪的错误:

t.cc:6:31: error: default argument for template parameter for class enclosing ‘struct __lambda0’
  function<int(int)> f = [](int i){return i+i;};
                               ^

这是一个不起眼的那些C ++规则的例外,没有人知道或者是一个GCC的bug?

编辑看起来像一个bug。 我已提出bug报告

Answer 1:

我认为这是一个G ++错误的默认成员初始化。 我不看好这一点,所以有下列的支持证据:

template<class T=void>
struct  c {
   std::function<int(int)> f;
   c() : f([](int i){return i+i;}) {
   }
};

int main() {}

如果这样的作品,你在做什么应该工作了。 而它,即使你构建一个c

就个人而言,我觉得默认成员初始化应谨慎和小心使用。 我认为这是很容易创造了很多混乱的它,因为大多数人都希望所有的初始化在构造函数中完成,并且成员初始化不一定靠近任何构造的任何地方。 因此,他们可以离开人摸不着脑袋想一些成员如何得到一个特定的值。

我可以看到的情况,尤其是简单的,主要是数据类,它会工作得很好。 但大多数情况下,我认为,如果你有什么样的构造函数体,你可能不应该使用默认成员初始化。



Answer 2:

此代码将得到错误反正对gcc 。 是的,没有默认参数就可以编译。 它可以被编译,因为struct c没有任何地方使用。 但是,如果你尝试创建这个结构的情况下,你会得到错误。

#include <functional>

template<class T>
struct c {
    std::function<int(int)> f = [](int i){return i+i;};
};

int main() {
    c<int> _c; // error
}

它看起来像一个错误gcc 。 这种方式可以帮助避免问题。

#include <functional>
#include <iostream>

template<class T=void>
struct c {
   c() : f([](int i){return i+i;}) {
   }

   std::function<int(int)> f;
};

int main() {
   c<> _c; 
   std::cout << _c.f(10) << std::endl;
}


文章来源: Class with non-static lambda member can't use default template paramers?