How do I print vector values of type glm::vec3 that have been passed by reference?

前端 未结 5 1597
星月不相逢
星月不相逢 2020-12-25 10:12

I have a small obj loader and it takes two parameters and passes them back to the input variables.. however this is my first time doing this and i\'m not sure how to print s

相关标签:
5条回答
  • 2020-12-25 10:24

    I think the most elegant solution might be a combination of the two answers already posted, with the addition of templating so you don't have to reimplement the operator for all vector/matrix types (this restricts the function definition to header files, though).

    #include <glm/gtx/string_cast.hpp>
    
    template<typename genType>
    std::ostream& operator<<(std::ostream& out, const genType& g)
    {
        return out << glm::to_string(g);
    }
    
    0 讨论(0)
  • 2020-12-25 10:25

    To get the overload resolution right, you can do something like:

    // Writes a generic GLM vector type to a stream.
    template <int D, typename T, glm::qualifier P>
    std::ostream &operator<<(std::ostream &os, glm::vec<D, T, P> v) {
      return os << glm::to_string(v);
    }
    
    
    0 讨论(0)
  • 2020-12-25 10:44

    glm::vec3 doesn't overload operator<< so you can't print the vector itself. What you can do, though, is print the members of the vector:

    std::cout << "{" 
              << vertices[i].x << " " << vertices[i].y << " " << vertices[i].z 
              << "}";
    

    Even better, if you use that a lot, you can overload operator<< yourself:

    std::ostream &operator<< (std::ostream &out, const glm::vec3 &vec) {
        out << "{" 
            << vec.x << " " << vec.y << " "<< vec.z 
            << "}";
    
        return out;
    }
    

    Then to print, just use:

    std::cout << vertices[i];
    
    0 讨论(0)
  • 2020-12-25 10:44

    GLM has operator<<() in <glm/gtx/io.hpp>

    #include <iostream>
    #include <glm/glm.hpp>
    #include <glm/gtx/io.hpp>
    
    int main()
    {
       glm::vec3 v(1.0f, 2.0f, 3.0f);
       std::cout << v << std::endl;
    }
    

    Output is:

    [    1.000,    2.000,    3.000]
    
    0 讨论(0)
  • 2020-12-25 10:49

    glm has an extension for this. Add #include "glm/ext.hpp" or "glm/gtx/string_cast.hpp"

    Then to print a vector for example:

    glm::vec4 test;
    std::cout<<glm::to_string(test)<<std::endl;
    
    0 讨论(0)
提交回复
热议问题