Google Test (gtest) 코드를 VxWorks 5.5로 이식하려고합니다. 심각한 단점은 개발 환경 Tornado 2.2가 고대 GCC 컴파일러 버전 2.96을 사용한다는 것입니다.이 C++ 템플릿 클래스 코드는 어떻게 작동합니까?
코드의 일부분을 찾아 냈는데 gtest.h
코드 부분에 있습니다. 이해가 안됩니다! 이 C++ 템플릿 클래스는 어떻게 작동합니까? 이 클래스의 객체가 생성 될 때 템플릿 유형 From
이 템플릿 유형 To
에 암시 적으로 변환하는 경우
// ImplicitlyConvertible<From, To>::value is a compile-time bool
// constant that's true iff type From can be implicitly converted to
// type To.
template <typename From, typename To>
class ImplicitlyConvertible {
private:
// We need the following helper functions only for their types.
// They have no implementations.
// MakeFrom() is an expression whose type is From. We cannot simply
// use From(), as the type From may not have a public default
// constructor.
static From MakeFrom();
// These two functions are overloaded. Given an expression
// Helper(x), the compiler will pick the first version if x can be
// implicitly converted to type To; otherwise it will pick the
// second version.
//
// The first version returns a value of size 1, and the second
// version returns a value of size 2. Therefore, by checking the
// size of Helper(x), which can be done at compile time, we can tell
// which version of Helper() is used, and hence whether x can be
// implicitly converted to type To.
static char Helper(To);
static char (&Helper(...))[2]; // NOLINT
// We have to put the 'public' section after the 'private' section,
// or MSVC refuses to compile the code.
public:
// MSVC warns about implicitly converting from double to int for
// possible loss of data, so we need to temporarily disable the
// warning.
#ifdef _MSC_VER
# pragma warning(push) // Saves the current warning state.
# pragma warning(disable:4244) // Temporarily disables warning 4244.
static const bool value =
sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
# pragma warning(pop) // Restores the warning state.
#elif defined(__BORLANDC__)
// C++Builder cannot use member overload resolution during template
// instantiation. The simplest workaround is to use its C++0x type traits
// functions (C++Builder 2009 and above only).
static const bool value = __is_convertible(From, To);
#else
static const bool value =
sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
#endif // _MSV_VER
};
는 이름 value
와 부울 변수는 답을 포함해야합니다. 대답을 얻으려면 MakeFrom()
과 Helper()
의 두 가지 전용 함수가 사용됩니다. 그러나이 두 함수는 여기서 선언 할 뿐이며, 둘 중 어느 것에 대해서도 정의를 찾을 수 없습니다. 그 밖의 것이 없다면이 구현은 연결되지 않아야합니다.
이 나도는 물론 다음
static char (&Helper(...))[2];
의 구문을 이해하지 않는,이 코드는 잘 컴파일합니다 (아래의 Microsoft Visual C++ 7.1 이상 또는 GCC 3.4 이상)와 구글의 사람들은 정확히 무엇을 알고 그들이 하고있다.
제발 저를 계몽하십시오! 이 코드를 이해하지 못하면 나를 미쳐 버릴 수 있습니다! :)