jeudi 5 mai 2016

In-class non-static member initialization in class template

This code:

using namespace std;

struct A
{
    A(string b)
    {
        cout << "A constructed: " << b << endl;
    }
};

template <typename T>
struct B
{
    A a{"Text"};
};

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

will throw this error: error: no matching function for call to 'A::A(<brace-enclosed initializer list>)', I don't understand why this code doesn't compile, but what is more consufing is that when I:

  • Make B regular (non-template) class OR
  • Initialize member a in initializer list (instead at point of delcaration) OR
  • change A's constructor to take const char* instead of string OR
  • Change A a{"Test"} to A a = "Test"(copy constructor)

it works? Why is it so?

Compiled using (g++ 4.8.1, with std=c++11 flag)

Aucun commentaire:

Enregistrer un commentaire