如何调试C++编译阶段的模板特化与静态断言过程
问题:静态断言检查类私有成员失败的原因及编译过程调试方法
我正在编写一个文件解析器,为避免同一函数的多实现编写了如下代码:
#include <string> #include <type_traits> #include <vector> #include <stdexcept> class VertexTexture { private: float m_u, m_v; public: // helper functions ... inline void set_u(float u) { m_u = u; } inline void set_v(float v) { m_v = v; } }; class ObjParser { private: std::vector<VertexTexture> m_textures; // store all VertexTextures std::string m_line; // current line in file // ... public: template <typename Container> void parseUVfloats(const std::string &line, std::back_insert_iterator<Container> elem_iter); // parse VertexTexture from `m_line` and push the result into `m_textures` // You can check implementation below void parseVertexTexture() { parseUVfloats(m_line, std::back_inserter(m_textures)); // ... } }; // <=== check if `T` has `m_u` and `m_v` in `float` type template <typename T, typename = void> struct HasUVFloatMembers : std::false_type {}; template <typename T> struct HasUVFloatMembers<T, std::void_t<decltype(&T::m_u), decltype(&T::m_v)>> : std::integral_constant< bool, std::is_floating_point<decltype(T::m_u)>::value && std::is_floating_point<decltype(T::m_v)>::value> {}; // ===> template <typename Container> void ObjParser::parseUVfloats(const std::string &line, std::back_insert_iterator<Container> elem_iter) { // static assertion, if I comment this, everything works fine static_assert(HasUVFloatMembers<typename Container::value_type>::value, "Container must have m_u, m_v members in float type."); std::vector<std::string> split_result = { "f", "1.0", "2.0"}; // split the line and get the result typename Container::value_type elem; try { elem.set_u(std::stof(split_result.at(1))); elem.set_v(std::stof(split_result.at(2))); } catch (const std::out_of_range &e) { exit(EXIT_FAILURE); } *elem_iter = elem; } int main() {}
编译时出现如下错误:
/home/insights/insights.cpp:48:17: 错误:静态断言失败,要求‘HasUVFloatMembers<VertexTexture, void>::value’成立:容器必须拥有float类型的m_u、m_v成员。 48 | static_assert(HasUVFloatMembers<typename Container::value_type>::value, | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /home/insights/insights.cpp:28:5: 注:此处实例化函数模板特化‘ObjParser::parseUVfloats<std::vector<VertexTexture>>’,请求来自第28行 28 | parseUVfloats(m_line, std::back_inserter(m_textures)); | ^ 1 error generated. Error while processing /home/insights/insights.cpp.
注释掉静态断言后代码可正常运行且结果正确,但我对此十分困惑,想知道是否有办法查看编译阶段模板特化与静态断言的执行过程?
更新
若在C++17中将m_u和m_v设为公有,编译即可成功。
内容的提问来源于stack exchange,提问作者LiuYuan
相关产品推荐
相关产品推荐

