【问题标题】:How to detect universal reference parameter type with std::is_same如何使用 std::is_same 检测通用引用参数类型
【发布时间】:2021-03-08 06:07:40
【问题描述】:

看看这些行:

template <typename T>
void f(T&& param) {
    if (std::is_same<T, int>::value) {
        cout << "param is an int" << endl;
    } else {
        cout << "param is not an int" << endl;
    }
    if (std::is_same<T, int&>::value) {
        cout << "param is an lvalue reference to int" << endl;
    }
    if (std::is_same<T, int&&>::value) {
        cout << "param is an rvalue reference to int" << endl;
    }
}
int main() {
    int i = 0;
    f(i);
    f(std::move(i));
    return 0;
}

第一个函数调用f(i) 产生:

param is not an int

param is an lvalue reference to int

这是我的预期,因为根据模板参数推导规则,T 解析为 T&amp;,导致 T&amp;&amp; &amp; 由于引用折叠而产生 T&amp;

第二个函数调用f(std::move(i)) 产生

param is an int

这不是我所期望的。我早就料到了

param 是对 int 的右值引用

至少

参数不是整数

谁能解释为什么我对第二个函数调用的期望没有得到满足?

【问题讨论】:

  • T&amp;&amp; for int&amp;&amp; : T -> int
  • 你有普遍的敬意,所以param不能是一个价值!当Tint 时,paramint&amp;&amp;

标签: c++ c++11 move-semantics


【解决方案1】:

试试这个:

#include <iostream>
#include <utility>
using namespace std;

template <typename T>
void f(T&& param) {
    using raw_type = std::remove_reference_t<T>;
    if (std::is_same<decltype(param), raw_type>::value) {
        cout << "param is an int" << endl;
    }
    else {
        cout << "param is not an int" << endl;
    }
    if (std::is_same<decltype(param), raw_type&>::value) {
        cout << "param is an lvalue reference to int" << endl;
    }
    if (std::is_same<decltype(param), raw_type&&>::value) {
        cout << "param is an rvalue reference to int" << endl;
    }
}
int main() {
    int i = 0;
    f(i);
    f(std::move(i));
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    相关资源
    最近更新 更多