【问题标题】:universal reference ignores top level cv qualifier通用参考忽略顶级 cv 限定符
【发布时间】:2013-07-04 14:12:03
【问题描述】:

谁能告诉我为什么通用引用会失去顶级简历的资格?我预计输出将在以下代码中的第二个和第三个函数调用中为 const 返回 true。

#include <iostream>
#include <type_traits>

using namespace std;

template<class T>
void print(T const &value){
    cout << "Printing from const & method: " << value << endl;
}

template<class T>
void print(T const *value){
    cout << "Printing from const * method: " << *value << endl;
}

template<class T>
void f(T&& item){
    cout << "T is const: " << boolalpha << is_const<decltype(item)>::value << endl;

    print(std::forward<T>(item));
}


int main(){

    f(5);

    const int a = 5;
    f(a);

    const int * const ptr = &a;

    f(ptr);

    return 0;
}

输出:

T is const: false
Printing from const & method: 5
T is const: false
Printing from const & method: 5
T is const: false
Printing from const * method: 5

【问题讨论】:

  • 引用永远没有顶级常量。
  • 啊啊啊啊。确切地。谢谢。你可以在它前面加上 const 吗?
  • 你指的是哪个函数调用?
  • 如何检查低级常量?

标签: c++ templates c++11 universal-reference


【解决方案1】:

正如 R. Martinho 指出的那样,引用没有顶级 const。

要检查较低级别的 const-ness,您可以使用 std::remove_reference:

cout << "T is const: " << boolalpha
     << is_const<typename remove_reference<decltype(item)>::type>::value
     << endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    相关资源
    最近更新 更多