2021-07-29

How to pass template type at runtime? [duplicate]

I have a ClassL<T> where I'm trying to pass a vector<T> to template ClassP<T> via the call ClassP::do_something(std::vector<T>).

// global variables
std::shared_ptr<ClassP<ObjA>> objA;
std::shared_ptr<ClassP<ObjB>> objB;
// elsewhere
objA = std::make_shared<ClassP<ObjA>>();
objB = std::make_shared<ClassP<ObjB>>();

template <typename T>
int ClassP<T>::do_something(const std::vector<T> msgs)
{   
    for (const auto& msg : msgs) {
        // print msg ...
    }

    return 0;
}

template <typename T>
void ClassL<T>::on_recv(T& records)
{
    auto data = records.get();

    std::vector<T> vecdata;

    std::copy(data.begin(), data.end(), 
        std::back_inserter(vecdata));

    if (std::is_same<T, ObjA>::value)
        objA->do_something(vecdata);

    else if (std::is_same<T, ObjB>::value) 
        objB->do_something(vecdata);
}

But doing the above will cause the following compile errors. I'm guessing my use of checking the template via is_same is not right but wasn't sure how to choose based on the type.

classl.hpp:75:27: error: cannot convert 
‘vector<ObjB,allocator<ObjB>>’ to ‘vector<ObjA,allocator<ObjA>>’
75 |   objA->do_this(vecdata);
   |                 ^~
   |                 |
   |                 vector<ObjB,allocator<ObjB>>

classl.hpp:80:39: error: cannot convert 
‘vector<ObjA,allocator<ObjA>>’ to ‘vector<ObjB,allocator<ObjB>>’
80 |   objB->do_this(vecdata);
   |                 ^~~~~~~~~
   |                 |
   |                 vector<ObjA,allocator<ObjA>>

Can anyone explain where I'm going wrong?



from Recent Questions - Stack Overflow https://ift.tt/3i7v7Jl
https://ift.tt/eA8V8J

No comments:

Post a Comment