decltype:使用指针访问类的静态成员

问题描述 投票:0回答:2

我有一个模板函数f。我将其传递给对象的引用或指针。该对象的结构为S。我想知道S::my_tuple的大小,它是该结构的静态成员。

当我通过std::tuple_size<decltype(T::my_tuple)>::value引用传递对象时,可以做到这一点。

如何为指针执行此操作?当前失败,因为my_tuple不是S*]的成员

Play with the code

#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
}
    

我有一个模板函数f。我将其传递给对象的引用或指针。该对象是结构S。我想知道S :: my_tuple的大小,它是该对象的静态成员...

c++ pointers templates static decltype
2个回答
1
投票

您可以仅使用类型特征来删除引用和指针,如下所示:


1
投票

只需使用type trait删除指针:

© www.soinside.com 2019 - 2024. All rights reserved.