2

The following struct

template<typename T, int rows, int cols>
struct ScalarCustomType
{
  T data[rows][cols];
}

works fine in combination with brace initialization, e.g.,

ScalarCustomType<int,3,3> B{{{1,2,3},{4,5,6},{7,8,9}}};

as well as

ScalarCustomType<int,3,3> B{1,2,3,4,5,6,7,8,9};

when compiled with c++11/14 support in g++ and clang++. The latter, however, warns about missing braces in the second case.

The library where this struct will be used requires the presence of the custom constructor

ScalarCustomType(const T& x) : { ... }

which is called in the following manner

ScalarCustmType<double,3,3> A(0) // not A{0} !!!

How can I reimplement the default brace initializer which gets deleted by the custom constructor?

Thanking you in advance and best wishes, Matthias

  • "*How can I reimplement the default brace initializer which gets deleted by the custom constructor?*" That 'default brace initializer' is aggregate-initialization, and your type ceases to be an aggregate once you add a custom constructor... – ildjarn Aug 23 '17 at 08:44
  • Thanks very much. Can I turn the type back into an aggregate by deriving it from a base class which implements the custom constructor? – Matthias Möller Aug 23 '17 at 08:48
  • No, such a class won't be [an aggregate](http://en.cppreference.com/w/cpp/language/aggregate_initialization) – Igor Tandetnik Aug 23 '17 at 13:30
  • If you define a custom constructor, the default constructor will not be generated by the compiler, but you can reinforce that by defining `ScalarCustomType() = default;`. – King Thrushbeard Aug 23 '17 at 14:03
  • I know that. The same works for the copy and move constructor which I can reinforce in that way. What I actually wanted to know is if it is possible to explicitly implement a constructor that will accept B{{{1,2,3},{4,5,6},{7,8,9}}} – Matthias Möller Aug 23 '17 at 15:16
  • @MatthiasMöller : You could have a constructor that takes a `std::initializer_list>`. – ildjarn Aug 23 '17 at 19:58
  • @MatthiasMöller : See [this demo](https://wandbox.org/permlink/XfkDehgA1PQwkdko) for some code to get started with. – ildjarn Aug 30 '17 at 07:26

0 Answers0