I am trying to create a C ++ class that can be implicitly converted to std::array . The conversion works, but it is not implied.
#include <array> class A { private: std::array<float, 7> data; public: operator std::array<float, 7>&() { return data; } operator const std::array<float, 7>&() const { return data; } }; int main() { A a; a[1] = 0.5f; // fails to compile auto it = a.begin(); // fails to compile A b; static_cast<std::array<float, 7>>(b)[1] = 0.5f; //ok auto it2 = static_cast<std::array<float, 7>>(b).begin(); //ok return 0; }
I understand that the above example is quite confusing, as it basically expands the private class member completely. But this is a simplified example, I'm just trying to solve the problem why implicit conversions in std::array do not work.
I tried the above example with clang-3.2 and gcc-4.8 . Neither compiles.
Even more perplexing is that if I use implicit conversion to a pointer, compilation obviously succeeds:
operator float *() { return data.begin(); } operator const float *() const { return data.cbegin(); }
But of course, this means losing many of the intricacies of std::array , which I will accept if there is no better solution.
source share