简体   繁体   中英

In-class initialisers using = for class templates

I apologise but I cannot understand why the following will not work (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 . 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.

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:

#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:

struct A { };

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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