Reputation: 41
I am using the below code and getting error. I don't understand why I am getting this error.
prog.cpp: In function ‘int main()’:
prog.cpp:15:44: error: could not convert ‘{"foo", true}’ from
‘<brace-enclosed initializer list>’ to ‘option’
option x[] = {{"foo", true},{"bar", false}};
^
prog.cpp:15:44: error: could not convert ‘{"bar", false}’ from
‘<brace-enclosed initializer list>’ o ‘option’
The code
#include <iostream>
#include <string>
struct option
{
option();
~option();
std::string s;
bool b;
};
option::option() = default;
option::~option() = default;
int main()
{
option x[] = {{"foo", true},{"bar", false}};
}
Upvotes: 4
Views: 1366
Reputation: 32852
When you provide† the default constructor and destructor, you are making the struct be a non-aggregate type, hence aggregate initialization is not possible.
However, you can check if a type is an aggregate using the standard std::is_aggregate_v
trait. (Since c++17).
See here for your case. It is not an aggregate, as you provided† those constructors.
You have the following three ways to make this work:
Remove the constructors and you are good to go.
struct option
{
std::string s;
bool b;
};
Default the constructors inside the struct (i.e. declaring†).
struct option
{
std::string s;
bool b;
option() = default;
~option() = default;
};
Otherwise, you need to provide a suitable constructor in your struct
.
struct option
{
std::string mStr;
bool mBool;
option(std::string str, bool b)
: mStr{ std::move(str) }
, mBool{ b }
{}
// other constructors...
};
† The following post explains when the constructor will be default
ed, when it is considered as user-declared and user-provided clearly: (Credits @NathanOliver)
C++ zero initialization - Why is `b` in this program uninitialized, but `a` is initialized?
Upvotes: 6