【问题标题】:std::tuple_element and referencesstd::tuple_element 和引用
【发布时间】:2016-05-05 22:43:12
【问题描述】:

我研究 std::tuple。

让我们有:

struct test_struct{};

我写

std::cout << typeid(std::tuple_element_t<0, std::tuple<struct test_struct &>>).name();

我期待的类型

struct test_struct &

但我收到了:

struct test_struct

如何提取类型 struct test_struct &(最好使用 std11)?

谢谢。

【问题讨论】:

  • typeid 去除引用,即typeid(int&amp;) == typeid(int)。真正的问题是,你为什么想要这个?如果您提供了它(即一些 MVCE),我们可以诊断它为什么没有按预期运行。但就目前而言,似乎一切都如预期的那样。

标签: c++ c++11 stdtuple


【解决方案1】:

由于typeid 运算符对引用类型工作

§5.2.8/4-5
如果 type 是引用类型,则结果引用代表被引用类型的 std::type_info 对象。

在所有情况下,typeid 都会忽略 cv 限定符(即typeid(T)==typeid(const T)

您可以编写一些包装器来找出引用类型的名称或带有 cv 限定符的类型。

template<typename T>
struct typeid_hlp
{
    static std::string name() { return typeid(T).name(); }
};

template<typename T>
struct typeid_hlp<T&>
{
    static std::string name() { return typeid_hlp<T>::name() + std::string(" &"); }
};

template<typename T>
struct typeid_hlp<T&&>
{
    static std::string name() { return typeid_hlp<T>::name() + std::string(" &&"); }
};

template<typename T>
struct typeid_hlp<const T>
{
    static std::string name() { return std::string("const ") + typeid_hlp<T>::name(); }
};

template<typename T>
struct typeid_hlp<volatile T>
{
    static std::string name() { return std::string("volatile ") + typeid_hlp<T>::name(); }
};

并像使用它

int main()
{
    std::cout << typeid_hlp<int>::name() << std::endl; // int
    std::cout << typeid_hlp<int&>::name() << std::endl; // int &
    std::cout << typeid_hlp<const int>::name() << std::endl; // const int
    std::cout << typeid_hlp<volatile const int * const &>::name() << std::endl; // const int const volatile * __ptr64 &
}

【讨论】:

  • 谢谢。我正确理解,从 tuple_element_t 我收到了正确的引用类型,它唯一的输出问题是我没有看到引用?
  • @JDiOrEximen 是的,typeid 去除 const 修饰符和引用修饰符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多