I have a number of classes that each define an inner struct Result
and are all derived from a Base
class. I’d like to have a single implementation method in the base class that returns the derived classes Result struct when called on a derived class. The below code works, but the type duplication in the actual call to get_result bothers me.
How can I make the compiler automatically deduce the template argument to the actual get_result call?
Additional restrictions:
Currently locked to c++17, but if there is a solution with newer standard versions I’d be interested to see them as well.
#include <string>
using namespace std;
class Base
{
public:
template<typename T>
typename T::Result get_result() const
{
// static_assert(std::is_base_of_v<Base, T>, "Derived not derived from BaseClass");
return T::Deserialize();
}
};
class DerivedA
: public Base
{
public:
struct Result
{
int i = 0;
};
static Result Deserialize(/*In reality there is some stream argument here*/)
{
Result r;
r.i = 42;
return r;
}
};
class DerivedB
: public Base
{
public:
struct Result
{
string s;
};
static Result Deserialize(/*In reality there is some stream argument here*/)
{
Result r;
r.s = "Yatta";
return r;
}
};
int main()
{
{
DerivedA a;
const auto res = a.get_result<DerivedA>();
}
{
DerivedB b;
const auto res = b.get_result<decltype(b)>();
}
return 0;
}
ceph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.