C++:如何测试类的示例是否包含模板函数中的给定成员?

yyyllmsg  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(132)

C++:如何测试类的示例是否包含模板函数中的给定成员?
我在谷歌上搜索了一下,看了一下应该有效的例子...但还是不明白为什么?!...
我想到的第一件事是使用traits和模板专门化,似乎这不起作用。
事实上,这是OK的:

  1. >> cat main.cpp
  2. #include <iostream>
  3. #include <type_traits>
  4. struct point2D {
  5. double x = 0.;
  6. double y = 0.;
  7. };
  8. struct point3D {
  9. double x = 0.;
  10. double y = 0.;
  11. double z = 0.;
  12. };
  13. template <typename T> struct has_z : std::false_type {}; // default case.
  14. template <> struct has_z<point3D> : std::true_type {}; // specialized case.
  15. template<typename T> void print(T const & obj) {
  16. std::cout << obj.x << " " << obj.y;
  17. //if (has_z<T>::value) std::cout << obj.z;
  18. std::cout << std::endl;
  19. };
  20. int main() {
  21. point2D pt2D;
  22. print(pt2D);
  23. point3D pt3D;
  24. print(pt3D);
  25. }
  26. >> g++ -o main main.cpp
  27. >> ./main
  28. 0 0
  29. 0 0

但是,取消注解注解行给出:

  1. >> g++ -o main main.cpp
  2. main.cpp: In instantiation of void print(const T&) [with T = point2D]’:
  3. main.cpp:27:8: required from here
  4. main.cpp:21:41: error: const struct point2D has no member named z
  5. 21 | if (has_z<T>::value) std::cout << obj.z;
  6. | ~~~~^

什么是最小的变化,让这工作(与C++20)和 * 为什么 *?

jtw3ybtb

jtw3ybtb1#

您需要用途:

  1. template<typename T> void print(T const & obj) {
  2. std::cout << obj.x << " " << obj.y;
  3. if constexpr(has_z<T>::value) std::cout << obj.z;
  4. std::cout << std::endl;
  5. };

这样,编译器就知道表达式是编译时constexpr,并且可以删除.z读取。否则,if是运行时,编译器无法生成一种可能性(.z的读取,更不用说它永远不会运行)

相关问题