C++:如何测试类的示例是否包含模板函数中的给定成员?
我在谷歌上搜索了一下,看了一下应该有效的例子...但还是不明白为什么?!...
我想到的第一件事是使用traits和模板专门化,似乎这不起作用。
事实上,这是OK的:
>> cat main.cpp
#include <iostream>
#include <type_traits>
struct point2D {
double x = 0.;
double y = 0.;
};
struct point3D {
double x = 0.;
double y = 0.;
double z = 0.;
};
template <typename T> struct has_z : std::false_type {}; // default case.
template <> struct has_z<point3D> : std::true_type {}; // specialized case.
template<typename T> void print(T const & obj) {
std::cout << obj.x << " " << obj.y;
//if (has_z<T>::value) std::cout << obj.z;
std::cout << std::endl;
};
int main() {
point2D pt2D;
print(pt2D);
point3D pt3D;
print(pt3D);
}
>> g++ -o main main.cpp
>> ./main
0 0
0 0
但是,取消注解注解行给出:
>> g++ -o main main.cpp
main.cpp: In instantiation of ‘void print(const T&) [with T = point2D]’:
main.cpp:27:8: required from here
main.cpp:21:41: error: ‘const struct point2D’ has no member named ‘z’
21 | if (has_z<T>::value) std::cout << obj.z;
| ~~~~^
什么是最小的变化,让这工作(与C++20)和 * 为什么 *?
1条答案
按热度按时间jtw3ybtb1#
您需要用途:
这样,编译器就知道表达式是编译时constexpr,并且可以删除
.z
读取。否则,if
是运行时,编译器无法生成一种可能性(.z
的读取,更不用说它永远不会运行)