그래서 저는이 간단한 C ++ Logger 클래스를 가지고 있습니다.
class Log{
public:
Log(const int& msgLevel = 1){
this->msgLevel = msgLevel;
}
template <class T>
Log& operator<<(const T& v){
if (msgLevel<=level) {
std::cout << v;
}
return *this;
}
~Log(){
}
static int level;
int msgLevel;
};
int Log::level = 1;
다음과 같이 사용할 수 있습니다.
Log(1)<<"My debug info: "<<otherVariable;
문제는 내가 사용하려고 할 때입니다 endl
.
Log(1)<<"My debug info: "<<otherVariable<<endl;
이 오류가 발생합니다.
error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'Log' (or there is no acceptable conversion)
이 오류를 해결하려면 다음과 같이 클래스에 다른 메서드를 추가해야합니다.
// For manipulators like endl
Log& operator<< (ostream& (*pf) (ostream&)) {
if (msgLevel<=level) {
cout << pf;
}
return *this;
}
그러나 endl
그것을 처리 하기 위해이 방법을 추가하는 것은 나에게 약간 과잉 인 것처럼 보입니다. 더 나은 대안이 있습니까?
또 다른 대안은 endl 대신 "\ n"을 사용하는 것입니다.
endl
은 함수 템플릿 이기 때문에 의 간단한 버전으로 operator<<
는 충분하지 않습니다..에 대해 서로 다른 템플릿 인수를 사용하여 일치시킬 수있는 여러 방법이 있기 때문입니다 endl
. 두 번째 오버로드를 추가하는 것이 아마도 최선의 방법 일 것입니다.
그러나 다음과 같이 일반적인 논리를 제거 할 수 있습니다.
template <class T>
Log& operator<<(const T& v){ return write(v); }
Log& operator<<(ostream& (*v)(ostream&)){ return write(v); }
template <typename T>
Log& write(const T &v)
{
if (msgLevel<=level) {
std::cout << v;
}
return *this;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다