SFINAE를 이해하려고 노력하고 있는데 그 중 어떤 클래스에 대해서도 'print'메서드를 호출하는 간단한 오버로드 된 연산자 < <을 작성하려고했습니다. 방법. 나는 질문 Is it possible to write a template to check for a function's existence?에 대한 답변을 통해 읽기 및 쓰기 시도 :SFINAE 오버로드 연산자 << 존재하는 경우 'print'메서드를 호출합니다.
template<class T, class = decltype(void(std::declval<T>().print), std::true_type{})>
inline std::ostream &operator<<(std::ostream &out, const T &obj) {
obj.print(out); return out; }
및
template<class T, class = decltype(void(std::declval<T>().print(std::declval<std::ostream &>())), std::true_type{})>
inline std::ostream &operator<<(std::ostream &out, const T &obj) {
obj.print(out); return out; }
을하지만 이것은 단순히 작동하지 않습니다 - 컴파일러는 모든 유형의 템플릿을 인스턴스화 아무런 문제가 없을 것 같다 따라서 문자열 리터럴과 같은 것을 인쇄하려고 할 때 '모호한 오버로드'오류가 발생합니다 ...
왜 그런 방법이 필요합니까? 'print()'함수를 표준 인'operator <<'로 단순히 "이름을 변경"해야합니다. –
관련이 없지만'inline'과 같은 템플릿을 선언 할 필요는 없습니다. 암시적일 것이다. – 5gon12eder
@JohnZwinck :'print'가 가상 일 경우 작동하지 않습니다. (보통 경우) –