In-class 初始化器使用 = for class 模板
In-class initialisers using = for class templates
我很抱歉,但我不明白为什么以下内容不起作用(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;
}
出于某种原因,通过引入模板,我无法将 =
用于字符串 s
的 in-class 初始值设定项。内置类型可以工作,实际上我可以通过使用大括号或在默认构造函数中显式初始化来绕过它。为什么它对使用 =
大惊小怪?
我看不出有任何理由这不起作用,最新版本的 gcc 和 clang 都可以毫无问题地编译您的代码。
这看起来与以下 gcc 错误有关:Brace-initializing a vector with a direct-initialization NSDMI doesn't work in a template 其中 class 初始化适用于非模板情况,但不适用于模板情况:
#include <vector>
struct X {X(int) {}};
template <class zomg>
class T {
std::vector<int> x{0};
};
int main()
{
T<int> t;
}
此错误报告:non-empty braced-init-list of non-static data member T[N] in class template results in error diagnostic, if T is a class 与以下测试用例更接近,但以同样的方式失败:
struct A { };
template<class>
struct B {
A a[1] = { A () };
};
int main () { B<void> b; }
我很抱歉,但我不明白为什么以下内容不起作用(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;
}
出于某种原因,通过引入模板,我无法将 =
用于字符串 s
的 in-class 初始值设定项。内置类型可以工作,实际上我可以通过使用大括号或在默认构造函数中显式初始化来绕过它。为什么它对使用 =
大惊小怪?
我看不出有任何理由这不起作用,最新版本的 gcc 和 clang 都可以毫无问题地编译您的代码。
这看起来与以下 gcc 错误有关:Brace-initializing a vector with a direct-initialization NSDMI doesn't work in a template 其中 class 初始化适用于非模板情况,但不适用于模板情况:
#include <vector>
struct X {X(int) {}};
template <class zomg>
class T {
std::vector<int> x{0};
};
int main()
{
T<int> t;
}
此错误报告:non-empty braced-init-list of non-static data member T[N] in class template results in error diagnostic, if T is a class 与以下测试用例更接近,但以同样的方式失败:
struct A { };
template<class>
struct B {
A a[1] = { A () };
};
int main () { B<void> b; }