为什么作为非类型参数传递的参数应该是全局的而不是局部的?不是只在编译时创建和分配内存吗?
在这种情况下 p 是一个 const 指针,所以它不能指向任何其他变量,那么它也会给出错误。为什么?
template<int* ptr>
class A{};
int x;
int *const p = &x;
int main() {
x = 9;
A<&x> ob;
A<p> ob2;//giving error
cin.get();
}
还有为什么只允许整数类型作为非类型参数,而不是char或float?
最佳答案
关于第一个问题,我不是编译器专家,但我可以猜测它使编译器的工作更轻松,也许这是来自旧版本 C++ 的限制,其中 constexpr
是无法使用。
尽管如此,C++11 标准的第 14.3.2/1 段非常清楚什么是允许的,什么是不允许的:
A template-argument for a non-type, non-template template-parameter shall be one of:
— for a non-type template-parameter of integral or enumeration type, a converted constant expression (5.19) of the type of the template-parameter; or
— the name of a non-type template-parameter; or
— a constant expression (5.19) that designates the address of an object with static storage duration and external or internal linkage or a function with external or internal linkage, including function templates and function template-ids but excluding non-static class members, expressed (ignoring parentheses) as & id-expression, except that the & may be omitted if the name refers to a function or array and shall be omitted if the corresponding template-parameter is a reference; or
— a constant expression that evaluates to a null pointer value (4.10); or
— a constant expression that evaluates to a null member pointer value (4.11); or
— a pointer to member expressed as described in 5.3.1; or
— an address constant expression of type std::nullptr_t.
关于第二个问题,char
is 是允许的。例如,下面是一个合法的程序:
template<char c>
struct X
{
// ...
};
int main()
{
X<'c'> x;
}
关于不允许使用浮点类型的原因,您可以在 this Q&A on StackOverflow 中找到一些信息。 .
关于c++ - 为什么模板非类型参数指针和引用参数需要是全局的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16711244/