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

Ant*_*ant 10 c++ gcc templates initialization c++11

我道歉但我不明白为什么以下不起作用(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;
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,通过引入模板,我无法=用于字符串的类内初始化器s.内置类型工作,实际上我可以通过在默认构造函数中使用大括号或显式初始化来规避它.为什么要大惊小怪使用=

Sha*_*our 4

我不认为有任何理由这不起作用,最新版本的 gcc 和 clang 都可以毫无问题地编译您的代码。

这看起来与以下 gcc bug 有关:使用直接初始化 NSDMI 进行大括号初始化向量在模板中不起作用,其中类初始化适用于非模板情况,但不适用于模板情况:

#include <vector>

struct X {X(int) {}};

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

int main()
{
  T<int> t;
}
Run Code Online (Sandbox Code Playgroud)

此错误报告:类模板中非静态数据成员 T[N] 的非空花括号初始化列表会导致错误诊断,如果 T 是一个类,则与以下测试用例更接近,则会以相同的方式失败:

struct A { };

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

int main () { B<void> b; }
Run Code Online (Sandbox Code Playgroud)