最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Templates with reference forwarding behaving unexpected - Stack Overflow

programmeradmin0浏览0评论

This is my example code:

#include <iostream>
#include <type_traits>

template <typename T>
void check_type(T&&) {
    if constexpr (std::is_reference<T>::value) {
        std::cout << "T is a reference\n";
        if constexpr (std::is_lvalue_reference<T>::value) {
            std::cout << "T is an lvalue reference\n";
        } else {
            std::cout << "T is an rvalue reference\n";
        }
    } else if constexpr (std::is_pointer<T>::value) {
         std::cout << "T is a pointer\n";
    }
    else {
        std::cout << "T is a value type (not a reference or pointer)\n";
    }
}

int main() {
    int x = 42;
    int& ref_x = x;
    int* ptr_x = &x;

    std::cout << "check_type(x): " << x << std::endl;
    check_type(x);   
    std::cout << "check_type(ref_x): " << ref_x << std::endl;
    check_type(ref_x);  
    std::cout << "check_type(std::move(x)): " << std::move(x) << std::endl;
    check_type(std::move(x)); 
    std::cout << "check_type(ptr_x): " << ptr_x << std::endl;
    check_type(ptr_x);    
    std::cout << "check_type(42): " << 42 << std::endl;
    check_type(42);       

    return 0;
}

The Output is the following:

check_type(x): 42 T is a reference T is an lvalue reference

check_type(ref_x): 42 T is a reference T is an lvalue reference

How is possible that x and x_ref are both lvalue references?? Is passing x or &x the same thing?

发布评论

评论列表(0)

  1. 暂无评论