0

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.

user3481478
  • 387
  • 1
  • 3
  • 19
  • I'm not sure I completely follow what `get_ref` is supposed to be doing, but it sounds like you want [if constexpr](https://stackoverflow.com/questions/43434491/difference-between-if-constexpr-vs-if) – Nathan Pierson Apr 22 '23 at 03:58
  • `get_ref` is just trying to get the value of a nested information. Eg. If I do `get_ref(c)`, it wants the value of type B in the object of C. I think my current approach is using `if constexpr` as the output given by `std::is_same_v` is `constexpr` – user3481478 Apr 22 '23 at 04:07
  • You're looking for [constexpr if](https://stackoverflow.com/questions/43434491/difference-between-if-constexpr-vs-if) – Jason Apr 22 '23 at 04:07
  • C++ will not automatically promote an `if` to an `if constexpr` just because the condition being checked in the `if` happens to be one that could be evaluated at compile time. You actually have to write `if constexpr` yourself. – Nathan Pierson Apr 22 '23 at 04:16

0 Answers0