简体   繁体   English

使用=用于类模板的类内初始化程序

[英]In-class initialisers using = for class templates

I apologise but I cannot understand why the following will not work (gcc 4.8.1): 我道歉但我不明白为什么以下不起作用(gcc 4.8.1):

#include <string>

using namespace std;

template <typename T> struct A{
    //A(): s("why") { } //fine
    //string s{"what"}; //also fine
    //A() = default; //(same error as below)
    string s = "why?!"; //error: conversion from 'const char [6]' to non-scalar type 'std::string {aka std::basic_string<char>}' requested|
};

struct B{
    string s = "why?!"; //all good
};

int main(){
    A<int> a;
    B b;
}

For some reason by introducing a template I'm unable to use = for the in-class initializer of the string s . 出于某种原因,通过引入模板,我无法使用=作为字符串s的类内初始值设定项。 Built-in types work and indeed I'm able to circumvent it by using braces or explicitly intialising in the default constructor. 内置类型工作,实际上我可以通过使用大括号或在默认构造函数中显式初始化来规避它。 Why does it kick up a fuss about using = ? 为什么要大概使用=

I don't see any reason this should not work, both recent versions of gcc and clang compiles your code without issue. 我没有看到任何原因这不起作用,最近版本的gcc和clang编译你的代码没有问题。

This looks related to the following gcc bug: Brace-initializing a vector with a direct-initialization NSDMI doesn't work in a template in which in class initialization works for the non-template case but not for the template case: 这看起来与以下gcc错误相关: 使用直接初始化NSDMI初始化向量不能在模板工作,在模板中,类初始化适用于非模板情况但不适用于模板情况:

#include <vector>

struct X {X(int) {}};

template <class zomg> 
class T {
  std::vector<int> x{0}; 
}; 

int main()
{
  T<int> t;
}

This bug report: non-empty braced-init-list of non-static data member T[N] in class template results in error diagnostic, if T is a class is a little closer with the following test case the fails in the same way: 此错误报告: 类模板中非静态数据成员T [N]的非空braced-init-list导致错误诊断,如果T是一个类,则与下面的测试用例稍微接近,以相同的方式失败:

struct A { };

template<class>
struct B {
  A a[1] = { A () };
};

int main () { B<void> b; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM