비 유형 템플릿 매개 변수
비 유형 템플릿 매개 변수는 상수 정수 표현식이어야한다는 것을 이해합니다. 누군가가 왜 그렇게 밝힐 수 있습니까?
template <std::string temp>
void foo()
{
// ...
}
error C2993: 'std::string' : illegal type for non-type template parameter 'temp'.
상수 적분 표현이 무엇인지 이해합니다. std::string
위의 스 니펫 과 같이 상수가 아닌 유형을 허용하지 않는 이유는 무엇입니까 ?
이렇게 할 수없는 이유는 컴파일 타임 동안 상수가 아닌 식을 구문 분석하고 대체 할 수 없기 때문입니다. 런타임 중에 변경 될 수 있으며 런타임 중에 새 템플릿을 생성해야합니다. 템플릿은 컴파일 시간 개념이므로 불가능합니다.
표준에서 비 유형 템플릿 매개 변수 (14.1 [temp.param] p4)를 허용하는 것은 다음과 같습니다.
유형이 아닌 템플릿 매개 변수는 다음 (선택적으로 cv-qualified) 유형 중 하나를 가져야합니다.
- 정수 또는 열거 유형,
- 객체에 대한 포인터 또는 함수에 대한 포인터,
- 객체에 대한 lvalue 참조 또는 함수에 대한 lvalue 참조,
- 멤버에 대한 포인터,
std::nullptr_t
.
그것은 허용되지 않습니다.
그러나 다음은 허용됩니다.
template <std::string * temp> //pointer to object
void f();
template <std::string & temp> //reference to object
void g();
C ++ Standard (2003)의 §14.1 / 6,7,8을 참조하세요.
삽화:
template <std::string * temp> //pointer to object
void f()
{
cout << *temp << endl;
}
template <std::string & temp> //reference to object
void g()
{
cout << temp << endl;
temp += "...appended some string";
}
std::string s; //must not be local as it must have external linkage!
int main() {
s = "can assign values locally";
f<&s>();
g<s>();
cout << s << endl;
return 0;
}
산출:
can assign values locally
can assign values locally
can assign values locally...appended some string
템플릿 인수를 조작 할 수 있어야합니다.
template <std::string temp>
void f() {
// ...
}
f<"foo">();
f<"bar">(); // different function!?
이제 impl은 std::string
구현에 알려지지 않은 특정 값을 저장하는 임의의 사용자 정의 클래스 또는 다른 임의의 사용자 정의 클래스에 대한 고유 한 문자 시퀀스를 만들어야합니다. 또한 임의의 클래스 개체의 값은 컴파일 타임에 계산할 수 없습니다.
It's planned to consider allowing literal class types as template parameter types for post-C++0x, which are initialized by constant expressions. Those could be mangled by having the data members recursively mangled according to their values (for base classes, for example we can apply depth-first, left-to-right traversal). But it's definitely not going to work for arbitrary classes.
A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be:
constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.
Also, string literals are objects with internal linkage, so you can't use them as template arguments. You cannot use a global pointer, either. Floating-point literals are not allowed, given the obvious possibility of rounding-off errors.
참고URL : https://stackoverflow.com/questions/5687540/non-type-template-parameters
'Nice programing' 카테고리의 다른 글
C #에서 DateTime 개체를 어떻게 복제 할 수 있습니까? (0) | 2020.10.06 |
---|---|
Android에서 String.isEmpty ()를 호출 할 수 없습니다. (0) | 2020.10.06 |
1234 == '1234 test'가 참으로 평가되는 이유는 무엇입니까? (0) | 2020.10.06 |
(iOS 7 출시 이후) PC / Mac에서 iTunes를 사용하지 않고 UDID를 얻을 수있는 방법이 있습니까? (0) | 2020.10.06 |
Windows에서 npm을 어떻게 업데이트합니까? (0) | 2020.10.06 |