c – 类的初始化器使用=类模板
发布时间:2020-12-16 05:39:04 所属栏目:百科 来源:网络整理
导读:我很抱歉,但我不明白为什么以下内容不行( gcc 4.8.1): #include stringusing 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?!"; //
我很抱歉,但我不明白为什么以下内容不行(
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; } 由于某种原因,通过引入模板,我无法使用字符串的类内初始值设置.内置类型工作,实际上我可以通过在默认构造函数中使用大括号或明确地初始化来规避它.为什么使用=? 解决方法
我没有看到任何理由不应该运行,最近的gcc和clang版本编译你的代码没有问题.
这看起来与以下gcc错误相关:Brace-initializing a vector with a direct-initialization NSDMI doesn’t work in a template其中类初始化适用于非模板情况,但不适用于模板情况: #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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |