How do I achieve the desired output via suitable modification of any code except Derived::Derived()
?
#include<iostream>
std::ostream& o = std::cout;
struct Base
{
void sanitycheck() { o << "base checks\n"; }
Base() { o << "make base\n"; }
};
// Code of struct Derived shall remain unaltered
struct Derived : Base
{
Derived() { o << "make derived\n"; }
};
// Dummy might help?
struct Dummy
{
Base& base;
Dummy(Base& base) :base(base) {}
~Dummy() { base.sanitycheck(); }
};
int main()
{
Derived x;
/* desired output:
make base
make derived
base checks // <-- missing piece
*/
}
Background: Base is in a library. Derived is user-supplied. Sanity checks can help mitigate user errors.
You cannot. Best you can do is provide a function to create the object:
template <std::derived_from<Base> T, typename... Args>
auto make_checked(Args&&... args) -> T {
T object(std::forward<Args>(args)...);
object.sanitycheck();
return object;
}
int main(){
auto x = make_checked<Derived>();
}
A decent compiler will use NRVO so no copy or move is performed. Otherwise, the object will be moved (or copied if it is not movable). You can force the type to be movable if needed:
template <std::derived_from<Base> T, typename... Args>
auto make_checked(Args&&... args) -> T requires(std::movable<T>) { ... }