【问题标题】:decltype and is_same giving confusing resultsdecltype 和 is_same 给出令人困惑的结果
【发布时间】:2015-10-11 16:30:01
【问题描述】:

您好,请考虑以下用例:

int main() {

    std::shared_ptr<int> shared_ptr_to_int;

    std::cout << typeid(int).name() << std::endl;
    std::cout << typeid(decltype(*shared_ptr_to_int)).name() << std::endl;

    if (std::is_same<decltype(*shared_ptr_to_int), int>::value) {
        std::cout << "is same!\n";
    }
    else {
        std::cout << "not the same!\n";
    }

    system("pause");
}

对于我的测试用例,我得到的结果“不一样”

我不确定为什么它不会导致价值为真。有人可以向我解释发生了什么吗?

PS:我的最终目标是将 shared_ptr 中存储的类型与另一种类型进行比较(在这个测试用例中,这个类型是 int)

感谢您的关注!

【问题讨论】:

  • decltype 的结果是引用类型。您的实现的 typeid 不区分那个和非引用。
  • 嗨,对于要提到使用以下内容的任何人: std::is_same<:shared_ptr>::element_type, int>::value 在我正在处理的项目中我不知道类型是 int,因此需要 decltype。 std::is_same 的第二个模板参数由模板函数调用给出,在该函数调用中它已经可以被推导和访问。

标签: c++ types decltype


【解决方案1】:

简介

当“解除引用”——通过std::shared_ptr&lt;...&gt;::operator*——一个shared_ptr,结果是一个引用,这意味着decltype(*shared_ptr_to_int)等价于int&amp;。 p>

reference-to-intint 不是同一类型,因此您会得到您所描述的行为。



细化

dereferenced std::shared_ptr 会产生一个reference,这样人们就可以真正进入并修改 shared_ptr 当前正在处理的对象。

为了修复您的示例,您应该使用 std::remove_reference 删除该(可能是意外的)参考

if (std::is_same<std::remove_reference<decltype(*shared_ptr_to_int)>::type, int>::value) {
  ...
}

您也可以将shared_ptr_to_int 作为decltype 的操作数传递,然后使用结果作为限定符来访问element_type

if (std::is_same<decltype(shared_ptr_to_int)::element_type, int>::value) {
  ...
}



为什么typeid(...).name() 为两者返回相同的名称

typeid 被一个引用类型调用时,它会丢弃它并将操作数当作一个非引用 类型(即它会简单地丢弃&amp;)。

还有一点值得一提的是,调用typeid(...).name() 的结果是implementation-defined——我们永远不应该对返回值过于信任。对于完全不同的类型,该函数甚至可能返回相同的 name — 实际上并不能保证(从标准的角度来看)。

进一步阅读

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多