사용법을 이해하기 위해 간단한 예제를 얻으려고합니다 std::enable_if
. 이 답변을 읽은 후 간단한 예를 제시하기가 너무 어렵지 않아야한다고 생각했습니다. std::enable_if
두 멤버 함수 중에서 선택하고 그중 하나만 사용할 수 있도록 사용하고 싶습니다 .
불행히도, 다음은 gcc 4.7로 컴파일되지 않으며 몇 시간 동안 노력한 후에 너희들에게 내 실수가 무엇인지 묻고있다.
#include <utility>
#include <iostream>
template< class T >
class Y {
public:
template < typename = typename std::enable_if< true >::type >
T foo() {
return 10;
}
template < typename = typename std::enable_if< false >::type >
T foo() {
return 10;
}
};
int main() {
Y< double > y;
std::cout << y.foo() << std::endl;
}
gcc는 다음과 같은 문제를보고합니다.
% LANG=C make CXXFLAGS="-std=c++0x" enable_if
g++ -std=c++0x enable_if.cpp -o enable_if
enable_if.cpp:12:65: error: `type' in `struct std::enable_if<false>' does not name a type
enable_if.cpp:13:15: error: `template<class T> template<class> T Y::foo()' cannot be overloaded
enable_if.cpp:9:15: error: with `template<class T> template<class> T Y::foo()'
왜 g ++가 두 번째 멤버 함수에 대한 잘못된 인스턴스를 삭제하지 않습니까? 표준에 따르면 std::enable_if< bool, T = void >::type
부울 템플릿 매개 변수가 true 인 경우에만 존재합니다. 그러나 왜 g ++는 이것을 SFINAE로 간주하지 않습니까? 오버로드 오류 메시지는 g ++이 두 번째 멤버 함수를 삭제하지 않으며 이것이 오버로드되어야한다고 믿는 문제에서 비롯된 것으로 생각합니다.
std::is_same< T, int >::value
하고 ! std::is_same< T, int >::value
있는이 같은 결과를 제공합니다.