I have a bunch of classes in a pipeline, where one class has a shared_ptr
to another class, and so on.
struct A{
};
struct B{
std::shared_ptr<A> a_data;
std::shared_ptr<A> get_predecessor_output() const{
return a_data;
}
};
struct C{
std::shared_ptr<B> b_data;
std::shared_ptr<B> get_predecessor_output() const{
return b_data;
}
};
I wanted to write a template function in C++ to view the instance of a given template parameter say ViewType from another given instance of parameter InstanceType. I have just hardcoded as of now and checking if the types match and accordingly return.
template<typename T, typename R>
const T& get_ref(const R& instance){
if(std::is_same_v<T,C> && std::is_same_v<R,B>){
return *instance.get_predecessor_output();
};
if(std::is_same_v<T,C> && std::is_same_v<R,A>){
auto tmp = *instance.get_predecessor_output();
return *tmp.get_predecessor_output();
}
};
int main(){
C c;
get_ref<B,C>(c);
return 0;
}
This fails compilation with the following error
error: no viable conversion from returned value of type 'A' to function return type 'const B'
return *tmp.get_predecessor_output();
But it shouldn't even go in that flow. I assume at compile time, it is checking all possible combinations for the inferred types. How can I resolve this compilation error?
Another solution I could think is to give ids in increasing order to classes and check that. I am assuming type checking can happen only at compile time, but just wondering if there is a more elegant solution to it. Even the recursive approach to this, fails with a similar error.