And*_*zos 24 c++ templates c++11
在C++ 11标准的6.8.3中,它说:
如果在解析期间,模板参数中的名称的绑定方式与试验解析期间绑定的名称不同,则程序格式不正确.
由于此要求而导致程序错误的示例是什么?
n. *_* m. 27
#include <iostream>
#include <typeinfo>
typedef const int cint;
template <int a> struct x
{
static cint b = 0;
};
template <> struct x<42>
{
typedef cint b;
};
cint w = 17;
int main ()
{
cint (w)(42), (z)(x<w>::b);
std::cout << typeid(z).name() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
第一个声明main()需要消除歧义,因此会执行试验解析.在这个解析期间,本地w是未知的,因为解析纯粹是语法(只解析事物,不执行语义动作).因此,w是一个全局常量,它的值是17,x<w>::b是一个值,并且z是一个变量.
在真正的解析期间,发生语义动作.因此,名称w绑定到新声明的局部常量,其值为42,x<w>::b成为类型,并且z是函数声明.