0

I am using c++ for my project and facing this error in one of my functions.

"a const_cast can only adjust type qualifiers; it cannot change the underlying type"

I am working with thrust library and all my vectors are device type. The problem is that when I change host_vector to device_vector, I get errors and the above error is one of them. I need to cast the iterator of find_if(inode) to Node*(Node is a struct). As I mentioned, this problem appears after changing the host_vector to the device_vector. Before that everything's fine. Unfortunately, I cannot find any solution to this problem so I'm stuck a bit:| I'm not even sure if I can cast this iterator to the desired struct type. By the way, if it helps, the type of inode after changing to device_vector is sth like this: thrust::detail::normal_iteratorthrust::device_ptr<Node>

Could someone help me, please...

Here is my function: I have tried (*inode), (&inode), (&(*inode)), and so on. And none of them worked.

Node* getItem(int const& p_itemValue)
{
    auto inode = thrust::find_if(thrust::device, _itemList.begin(), _itemList.end(), __host__ __device__ [&p_itemValue](Node const& p_node)
        {
            return p_node._itemValue == p_itemValue;
        });

    //int index = inode - _itemList.begin();

    if (inode != _itemList.end())
    {
        Node* node = const_cast<Node*>(inode);
        return node;
    }

    return nullptr;
}
Lida
  • 1
  • 1
  • use `static_cast` instead ? – Lorah Attkins Jan 04 '23 at 13:14
  • gives another error "no suitable conversion function from "thrust::detail::normal_iterator>" to "Node *" exists" – Lida Jan 04 '23 at 13:38
  • You're trying to cast the iterator to the underlying type (or what you believe is the underlying type), that's not how iterator works. If you want to access the underlying value, use `*inode` but then you will get a `thrust::device_ptr`. I don't understand why you would want a `const_cast` here since `thrust::device_ptr` is not const in anyway. If you want a `Node*`, I guess you need to find a way to obtain it frm a `thrust::device_ptr`. – Holt Jan 04 '23 at 13:45
  • `(*inode).get()` (provided thrust is the Nvidia one)? But as @Holt has mentioned, why is the `const_cast` there? It's usually a red flag and oftentimes a "don't you dare" during code review ;) Besides, IIRC iterators don't have to convert to pointers directly, thus I'd recommend `&(*inode)` for obtaining the pointer to the iterator-pointed type... – alagner Jan 04 '23 at 13:53

0 Answers0