함수가 존재하는지 안 하는지 어떻게 알 수 있을까요?
조회수 2993회
C++ 템플릿에서 함수의 존재 유무에 따라 다른 일을 하도록 만들고 싶습니다.
제가 만든 코드에서 FUNCTION_EXISTS()
의 역할을 하는 기능이 있나요?
소스코드
template<class T>
std::string optionalToString(T* obj)
{
if (FUNCTION_EXISTS(T->toString))
return obj->toString();
else
return "toString not defined";
}
1 답변
-
SFINAE(Substitution Failure Is Not An Error)를 쓰세요 SFINAE로 클래스가 특정 메소드를 지원하는지 확인할 수 있습니다
#include <iostream> struct Hello { int helloworld() { return 0; } }; struct Generic {}; // SFINAE test template <typename T> class has_helloworld { typedef char one; typedef long two; template <typename C> static one& test( typeof(&C::helloworld) ) ; //helloworld메소드가 있는지 확인 해줌 template <typename C> static two& test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; int main(int argc, char *argv[]) { std::cout << has_helloworld<Hello>::value << std::endl; // result : 1 std::cout << has_helloworld<Generic>::value << std::endl; // result : 0 return 0; }
댓글 입력