다음 예제 (C ++ 17)로 범위를 좁힌 일부 템플릿 항목에 문제가 있습니다.
template <typename T> struct item {
operator item<const T> () const { return item<const T>(); }
};
void conversionToConstRefWorks (const item<const int> &) { }
template <typename T>
void butNotWhenTemplated (const item<const T> &) { }
int main () {
item<int> i;
item<const int> ci;
// these all compile fine:
conversionToConstRefWorks(ci);
conversionToConstRefWorks(i);
butNotWhenTemplated(ci);
// but this one fails:
butNotWhenTemplated(i);
}
그 예에서 :
item<T>
에 대한 암시 적 변환 연산자가 item<const T>
있으며conversionToConstRefWorks()
같지만butNotWhenTemplated()
. 여기서는 item<const int>
잘 전달 될 수 있지만 전달은 item<int>
컴파일에 실패합니다.해당 예제의 컴파일은 다음과 함께 실패합니다 (GCC 9.3).
g++ --std=c++17 -W -Wall -pedantic -Wno-unused-variable const_interop.cpp -o const_interop
const_interop.cpp: In function ‘int main()’:
const_interop.cpp:54:24: error: no matching function for call to ‘butNotWhenTemplated(item<int>&)’
54 | butNotWhenTemplated(i);
| ^
const_interop.cpp:40:6: note: candidate: ‘template<class T> void butNotWhenTemplated(const item<const T>&)’
40 | void butNotWhenTemplated (const item<const T> &) {
| ^~~~~~~~~~~~~~~~~~~
const_interop.cpp:40:6: note: template argument deduction/substitution failed:
const_interop.cpp:54:24: note: types ‘const T’ and ‘int’ have incompatible cv-qualifiers
54 | butNotWhenTemplated(i);
| ^
루트 오류는 다음과 같습니다.
'const T'및 'int'유형에 호환되지 않는 cv 한정자가 있습니다.
나는 그것이 문자 그대로 의미하는 바를 이해하지만 그것이 왜 일어나고 있는지 이해하지 못합니다. 내 기대는 것입니다 item<int> :: operator item<const int> () const
호출 할 때 변환 연산자를 적용 할 것이다 butNotWhenTemplated(i)
호출 할 때이 적용된 것처럼 conversionToConstRefWorks(i)
, 그리고이 int
선택 될 것이다 T
.
내 주요 질문은 : 왜 이것이 컴파일되지 않습니까?
내 다른 질문은이 게시물의 범위를 벗어난 이유로 butNotWhenTemplated
템플릿이어야하고 <const T>
모든 item
매개 변수 를 지정해야 하며 호출 할 때 템플릿 매개 변수를 명시 적으로 지정할 수 없다는 것입니다. 이러한 제약 조건으로이 작업을 수행 할 수있는 방법이 있습니까?
여기에 ideone (GCC 8.3)이 있습니다.
item<int> i;
template <typename T> void butNotWhenTemplated (const item<const T> &) { }
butNotWhenTemplated(i);
에 따르면 템플릿 인수 대체 규칙, 더는 T
찾을 수 없습니다 item<const T>
일치하는 item<int>
. 변환 (내장 또는 사용자 정의)을 고려하기 전에 하드 오류 방식으로 실패합니다.
유형 추론은 암시 적 변환 (위에 나열된 유형 조정 제외)을 고려하지 않습니다. 이것이 나중에 발생하는 과부하 해결 작업입니다. 그러나 템플릿 인수 추론에 참여하는 모든 매개 변수에 대해 추론이 성공하고 추론되지 않은 모든 템플릿 인수가 명시 적으로 지정되거나 기본값이 지정되면 나머지 함수 매개 변수가 해당 함수 인수와 비교됩니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다