I am wondering if this an stdlib bug, an oversight, my own error or intended by the standards committee.
If a type T
's constructor (any of its constructors) is non-public, an unrelated container cannot emplace an element using that constructor, clearly. However, my reasoning was that if I befriend said container, various emplace's should be allowed, but due to the way the standard library containers are generally implemented over myriad of sub- and helper-classes this doesn't seem to work.
Consider this:
#include <optional>
class T {
friend std::optional<T>;
T(int) {}
};
int main() {
std::optional<T> opt;
opt.emplace(7);
}
If this is compiled with g++ 10.2, it complains that no suitable function std::optional<T>::emplace(int)
exists. Notably it does not complain that T::T(int)
is private within this context as I would have expected.
-> Live demo
Note that this would work with a self defined class:
class H {
void f() {
T(7); // fine iff H is a friend of T (otherwise "private within this context" error)
}
};
So, to restate my question from above, should this work?