【发布时间】:2020-10-02 13:13:20
【问题描述】:
我有一个模板函数f。我将它传递给一个引用或一个指向对象的指针。该对象的结构为S。我想知道S::my_tuple 的大小,它是该结构的静态成员。
当我使用std::tuple_size<decltype(T::my_tuple)>::value 通过引用传递对象时,我可以做到这一点。
如何为指针执行此操作?这目前失败了,因为my_tuple 不是S* 的成员
#include <tuple>
#include <type_traits>
#include <iostream>
struct S {
constexpr static auto my_tuple = std::make_tuple(1, 2, 3, 4);
};
template <typename T>
int f(const T object) {
// fails if T is a pointer
if (std::is_pointer<T>::value) {
// error
return std::tuple_size<decltype(T::my_tuple)>::value;
}
// works if T is a reference
return std::tuple_size<decltype(T::my_tuple)>::value;
}
int main() {
S my_struct;
std::cout << f(my_struct); // 4, correct size of properties
S* my_ptr = new S;
std::cout << f(my_ptr); // does not compile
}
编辑:
感谢您的支持。这是solution
【问题讨论】:
-
在这种特殊情况下,您实际上并不需要分支。正如 cigien 在他的回答中所建议的那样,只需使用
return std::tuple_size_v<decltype(std::remove_pointer_t<T>::my_tuple)>;。从非指针类型中删除指针不会有什么坏处。
标签: c++ pointers templates decltype