模板类中的模板函数is_same [英] Template function is_same in template classes

查看:152
本文介绍了模板类中的模板函数is_same的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码产生错误输出?

Why this code produces a false output?

//this-type.cpp  

#include <iostream>
#include <type_traits>

using namespace std;

template<typename testype>
class A
{
public:
    A()
    {
        cout << boolalpha;
        cout << is_same<decltype(*this), A<int>>::value << endl;
    }
};

class B : public A<int>
{
};

int main()
{
    B b;
}

输出:

$ g++ -std=c++11 this-type.cpp
$ ./a.out
false

A到B内的* this的类型是A < int>,不是吗?

The type of "*this" inside A through B is A< int >, isn't it?

推荐答案

* this 类型 A 的左值,因此 decltype(* this)将给出引用类型 A& ; 。回想一下,在$ lvalue上的 decltype 给出了引用类型:

*this is an lvalue of type A, so decltype(*this) will give the reference type A &. Recall that decltype on an lvalue gives the reference type:

    cout << is_same<decltype(*this), A<int>>::value << endl;
    cout << is_same<decltype(*this), A<int> &>::value << endl;

输出:

false
true

这篇关于模板类中的模板函数is_same的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆