Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么局部变量实例化失败,而静态变量实例化失败?_C++_Templates_Compiler Errors - Fatal编程技术网

C++ 为什么局部变量实例化失败,而静态变量实例化失败?

C++ 为什么局部变量实例化失败,而静态变量实例化失败?,c++,templates,compiler-errors,C++,Templates,Compiler Errors,我试图找到一种简单的方法(使用C++11之前的版本,即nodecltype)来记录模板对类型的哪些要求,以使其正常工作。也许有更好的方法可以做到这一点。不过,我的问题是: #include <iostream> template <typename T> struct Foo { static const int test = sizeof(T::size); }; template <typename T> struct DetectAndErr

我试图找到一种简单的方法(使用C++11之前的版本,即no
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 :)
}

这是因为标准要求
test
仅在使用时才会实例化。模板类的成员变量/成员函数/静态成员在未使用它们的情况下不会被实例化

在您的情况下,当您尝试执行
x.test
编译器尝试查找
test
时,随后无法执行,因为缺少
x::size


这种行为基本上被接受和普遍,当然符合标准。

另一个答案是有效的,但这里有一些标准:

N4140§14.7.1[温度仪表]/1和2

类模板专门化的隐式实例化会导致 声明的隐式实例化,但不是 的定义、默认参数或异常规范 类成员函数、成员类、作用域成员枚举、, 静态数据成员和成员模板;它导致了隐式的 非作用域成员枚举定义的实例化和 成员匿名工会

当 在需要成员的上下文中引用专门化 存在的定义;特别是初始化(以及任何 静态数据成员的相关副作用)不会发生,除非 静态数据成员本身的使用方式需要 要存在的静态数据成员的定义


因此,
test
仅在第一行中声明,但在尝试实例化时会产生错误。对于
detectanderro
,您隐式调用了它的默认构造函数
typedef DetectAndError foo
DetectAndError*ptr
应该可以毫无问题地编译

对于函数来说,这条规则对几乎所有人来说都是非常直观的:)嗯,好吧,如果它是这样定义的,那么我必须接受它是这样的;)。我期待着一些不同的东西
error: 'size' is not a member of 'Bar'