Reputation: 1432
Using C++11 in MS Visual Studio 2013, I have a class testNetInfo that has a non-explicit constructor from std::string, and I would like to construct a vector of these from a std::initializer list of strings.
If I construct a temporary vector from the initializer_list, I can use that to set up the real vector:
void SimComparisonTests::compareCombinationalGateWithXorZ(const std::string& outNetName, std::initializer_list<std::string> initList) {
std::vector<std::string> inNetNames(initList);
std::vector<testNetInfo> netInfo;
for (auto nn = inNetNames.begin(); nn != inNetNames.end(); ++nn) {
netInfo.push_back(testNetInfo(*nn));
}
But trying to create netInfo directly from initList like this:
std::vector<testNetInfo> netInfo(initList);
gives the following error:
It looks like I can avoid this error if I change the type of initList to initializer_list<testNetInfo>
, and add a constructor from const char *, so that I can pick up a call like:
compareCombinationalGateWithXorZ("triOut3", {"triIn3", "triEn3"});
But a possible catch with that fix is that the conversion from string (or const char *) to a testNetInfo object has to be done after run-time assignment of a class static pointer in testNetInfo that is used to do the name lookup to initialize the rest of the object. This will be done by the time the above function is called, and the above initialization looks ok in my implementation, but would I be pushing undefined behavior by declaring an initializer_list<testNetInfo>
with a class that has a run-time prerequisite like this (i.e., is it possible that an implementation might try to build the initializer_list before the caller is executed)? If so, is there a cleaner way to do this?
Upvotes: 0
Views: 2202
Reputation: 137320
Just because A
is convertible to B
doesn't mean initializer_list<A>
is convertible to initializer_list<B>
. The latter two are completely unrelated types.
As to the fix, just use the range constructor.
std::vector<testNetInfo> netInfo(initList.begin(), initList.end());
Upvotes: 1