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 =
?
Here is a simple example for in-class initialization. It's useful for less typing, especially when more than one constructor signatures are available. It's recommend in the core guidelines, too. class Foo { public: Foo () = default; // No need to initialize data members in the initializer list.
In this tutorial, we will learn about class templates in C++ with the help of examples. Templates are powerful features of C++ which allows us to write generic programs. There are two ways we can implement templates: Similar to function templates, we can use class templates to create a single class to work with different data types.
Another issue is with simple class member initialization. It is not uncommon to have more than a single constructor. Forgetting to initialize variables in each has caused me problems more than once. Having an initialization function is one solution.
There are two ways we can implement templates: Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With