Search code examples
cudathrust

Thrust vector of type uint2: "has no member x" compiler error?


I have just started using the Thrust library. I am trying to make a vector of length 5 on the device. Her I am just setting the members of the first element vec[0]

  #include<thrust/device_vector.h>
  #include<iostream>
  .
  . 
  . 

  thrust::device_vector<uint2> vec(5);
  vec[0]=make_uint2(4,5);
  std::cout<<vec[0].x<<std::endl;

However for the above code I get the error

error: class "thrust::device_reference<uint2>" has no member "x"

1 error detected in the compilation of "/tmp/tmpxft_000020dc_00000000-4_test.cpp1.ii".

Where am I going wrong? I thought that accessing a member of a native CUDA vector data type such as uint2 with .x and .y was the correct way of doing .


Solution

  • As talonmies notes in his comment, you can't directly access the members of elements owned by a device_vector, or any object wrapped with device_reference. However, I wanted to provide this answer to demonstrate an alternative approach to your problem.

    Even though device_reference doesn't allow you to access the members of the wrapped object, it is compatible with operator<<. This code should work as expected:

    #include <thrust/device_vector.h>
    #include <iostream>
    
    // provide an overload for operator<<(ostream, uint2)
    // as one is not provided otherwise
    std::ostream &operator<<(std::ostream &os, const uint2 &x)
    {
      os << x.x << ", " << x.y;
      return os;
    }
    
    int main()
    {
      thrust::device_vector<uint2> vec(5);
      vec[0] = make_uint2(4,5);
      std::cout << vec[0] << std::endl;
      return 0;
    }