我有一个小的obj加载程序,它接受两个参数并将它们传递回输入变量。。然而,这是我第一次这样做,我不知道现在如何打印所述值。这是我测试加载程序是否工作的主要功能。我有两个类型为glm::vec3
的向量来保存顶点和法线数据。
std::vector<glm::vec3> vertices;
std::vector<glm::vec3> normals;
int main() {
bool test = loadOBJ("cube.obj", vertices, normals);
for (int i = 0; i < vertices.size(); i++) {
std::cout << vertices[i] << std::endl; // problem line
}
return 0;
}
上面评论的一行就是产生无用信息的原因。如果我这样处理并运行程序,我会收到一堆错误(太未格式化且太长,无法粘贴到此处),如果我添加引用运算符,我会得到这样的输出:
0x711ea0
0x711eac
0x711eb8
0x711ec4 // etc
知道我做错了什么吗?
glm对此有一个扩展。添加#include "glm/ext.hpp"
或"glm/gtx/string_cast.hpp"
然后打印矢量,例如:
glm::vec4 test;
std::cout<<glm::to_string(test)<<std::endl;
我认为最优雅的解决方案可能是将已经发布的两个答案结合起来,并添加模板,这样您就不必为所有向量/矩阵类型重新实现运算符(不过,这将函数定义限制为头文件)。
#include <glm/gtx/string_cast.hpp>
template<typename genType>
std::ostream& operator<<(std::ostream& out, const genType& g)
{
return out << glm::to_string(g);
}
glm::vec3
不会重载operator<<
,因此无法打印矢量本身。不过,你可以做的是打印矢量的成员:
std::cout << "{"
<< vertices[i].x << " " << vertices[i].y << " " << vertices[i].z
<< "}";
更好的是,如果你经常使用它,你可以自己过载operator<<
:
std::ostream &operator<< (std::ostream &out, const glm::vec3 &vec) {
out << "{"
<< vec.x << " " << vec.y << " "<< vec.z
<< "}";
return out;
}
然后打印,只需使用:
std::cout << vertices[i];
GLM在<glm/gtx/io.hpp>
中具有operator<<()
#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;
}
输出为:
[ 1.000, 2.000, 3.000]
要获得正确的过载分辨率,可以执行以下操作:
// 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);
}
详细阐述JAB的答案,我使用以下内容来避免'operator <<' is ambiguous
错误:
#include <glm/glm.hpp>
#include <glm/gtx/string_cast.hpp>
/**
* can_cout<T> tells whether there already exists an override of operator<< that
* supports T.
*/
template <typename, typename = void>
struct can_cout : public std::false_type {};
template <typename T>
struct can_cout<T, std::void_t<decltype(operator<<(std::declval<std::ostream>(), std::declval<T>()))> > : public std::true_type {};
/**
* Implement operator<< iff GlmType is handled by glm::to_string but there is
* not already an override of operator<< that hanldes this type.
*/
template<
typename GlmType,
typename = std::enable_if_t<!can_cout<GlmType>::value>,
typename = decltype(glm::to_string(std::declval<GlmType>()))
>
std::ostream& operator<<(std::ostream& out, const GlmType& g)
{
return out << glm::to_string(g);
}