는 가변 인자 템플릿으로 Tuple
을 구현하는 방법은이를 선택합니다있을 경우이
// Base case, Tuple<>
template< typename... Ts >
class Tuple {
};
// recursive inheritance :D
template< typename T, typename... Ts >
class Tuple< T, Ts... > : private Tuple<Ts...> {
public:
// we implement get() by checking wether element type match with
// request type
template< typename t >
typename std::enable_if< std::is_same< t, T >::value, t& >::type
get() {
return element;
}
// above is not enough since it only check this class's element type,
// we can check the rest of the tuple by inspecting its the parent classes.
template< typename t >
typename std::enable_if< !(std::is_same< t, T >::value), t& >::type
get() {
return Tuple<Ts...>::template get<t>(); // call its parent's get()
// ::template to shut compiler up
}
private:
T element;
};
Tuple< short, int, float, double, char, std::string > t;
auto x = t.get<std::string>(); // x will be an empty string.
이 같은 것이, 중복 요소 유형을지지 않습니다이다 하나는 전면에 있습니다. 요청 유형이 튜플에 없으면 컴파일되지 않습니다.
동일한 유형을 두 번 사용하면 어떻게됩니까? – cppguy
이 클래스는 유형별로 하나의 요소 만 사용하는 사용 사례에서 특별히 사용됩니다. – jmegaffin
필자는 7 년전에이 작업을 해봤지만 그 당시에는 메일 링리스트에서 언급했지만 어느 누구도 유틸리티를 보지 못했고 자세한 설명을 귀찮게 할 수 없었습니다. Alexandrescu의 Loki 라이브러리를 사용 했으므로이를 수행 할 수있는 방법이 있습니다. 당신이 가서 문제를 일으킨다면, 당신은 대답 할 가치가있는 적절한 질문을 갖게 될 것입니다. 좋은 점은 인덱스 번호, 방문자 패턴 등으로 유형을 반환 할 수있는 기능을 제공 할 수 있다는 것입니다. 그리고 cppguy의 관심사를 다시 말해서 값을 별개의 유형으로 쉽게 래핑 할 수 있습니다. –