2013-05-23 2 views
1

비 형식 인수로 전달되는 인수는 전역이어야하며 로컬이 아니어야하는 이유는 무엇입니까? 컴파일시에만 메모리가 생성되고 할당되지 않습니다.왜 템플릿 nontype 매개 변수 포인터 및 참조 인수는 전역이어야합니까?

이 경우 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가 아닌 형식이 아닌 매개 변수로 허용되는 이유는 무엇입니까?

+0

또한 오류를 모두 표시하고 편집하지 않아도됩니다. 그러면 정확히 무엇이 잘못되었는지 쉽게 말하게 될 것입니다. –

+0

오류 : 템플릿 매개 변수 'ptr': 'p': 내부 링크가있는 개체를 포함하는 식을 형식이 아닌 인수로 사용할 수 없습니다. – Daemon

+0

템플릿 매개 변수를 컴파일하는 동안 알려야합니다. 전역 변수의 주소는 컴파일러가 알고있는 고정 된 오프셋입니다. 지역의 주소 인 OTOH는 호출 스택에 의존합니다. 컴파일러는 어떻게 보이는지 알지 못합니다. – jrok

답변

1

첫 번째 질문에 대해서는 필자가 컴파일러 전문가는 아니지만 컴파일러의 삶이 더 쉬워 짐을 짐작할 수 있으며, 아마도 constexpr을 사용할 수없는 이전 버전의 C++에서 오는 제한 사항 일 수 있습니다. char는 대신, 두 번째 질문에 관한

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.

: 그럼에도 불구하고

의 C++ 11 표준의 14.3.2/1 단락은 무엇을 허용하고 무엇을하는 것이 아닙니다에 관해서는 아주 명확하다 허용.

template<char c> 
struct X 
{ 
    // ... 
}; 

int main() 
{ 
    X<'c'> x; 
} 

이유 부동 소수점 형식은 허용되지 왜, 당신은 this Q&A on StackOverflow의 일부 정보를 찾을 수 있습니다에 관하여 : 예를 들어, 다음은 합법적 인 프로그램입니다.

+0

당신이 제공 한 링크를 확인했는데, 컴파일러가 평등 비교를 수행 할 때 데이터 유형과 값에 대해 수행하지 않을 때 이해할 수없는 한 가지 이유가 있습니다. – Daemon

+1

@ Gaurav : 아니요, 값에 대해 수행 할 것입니다. 즉, 유형이 아닌 매개 변수가있는 전체 요점입니다. 형식 대신 값으로 값을 제공하고 있습니다. –

+0

내가 잘못 이해하면 정정 해주세요. 예를 들어 A <2.3> ob과 A <5.67> ob2를 실행하면 클래스 A의 두 인스턴스가 생성 될 수 있습니다. – Daemon

관련 문제