加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么实例化对局部变量失败而对静态失败?

发布时间:2020-12-16 10:37:07 所属栏目:百科 来源:网络整理
导读:我试图找到一种简单的方法(使用pre C 11,即没有decltype)来记录模板对类型的要求是否正常工作.也许有更好的方法来做到这一点.但是,这是我的问题: #include iostreamtemplate typename T struct Foo { static const int test = sizeof(T::size);};template t
我试图找到一种简单的方法(使用pre C 11,即没有decltype)来记录模板对类型的要求是否正常工作.也许有更好的方法来做到这一点.但是,这是我的问题:

#include <iostream>

template <typename T> struct Foo {
    static const int test = sizeof(T::size);
};

template <typename T> struct DetectAndError {
    DetectAndError() { int test = sizeof(T::size); }
};

struct Bar {};

int main() {
    Foo<Bar> x;                            // NO ERROR ? :/
    // std::cout << x.test << std::endl;   // ERROR :)
    // DetectAndError<Bar> y;              // ERROR :)
}

为什么Foo< Bar> X;不是错误?
对于其他线路,我得到了我想要的:

error: 'size' is not a member of 'Bar'

解决方法

这是因为标准要求测试仅在使用时才会被实例化.如果不使用它们,则不会实例化模板类的成员变量/成员函数/静态成员.

在你的情况下,你尝试做x.test编译器的那一刻试图找到测试,然后不能这样做,因为缺少x :: size.

根据标准,这种行为几乎被接受,并且是常见的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读