Stroustrup "A Tour of C ++"에서 그는 find_all의 예제를 다음과 같이 작성했습니다.
template<typename C, typename V>
vector<typename C::iterator> find_all(C& c, V v)
// find all occurrences of v in c
{
vector<typename C::iterator> res;
for (auto p = c.begin(); p!=c.end(); ++p)
if (∗p==v)
res.push_back(p);
return res;
}
무엇 typename C::iterator
에 template<typename C, typename V> vector<typename C::iterator> find_all
? 나는 <>이 함수 이름 앞뒤에있는 것을 보지 못했습니다. 이 구조는 무엇이며 어떻게 표현됩니까? 책에서 그는 썼다
The typename is needed to inform the compiler that C’s iterator is supposed to be a type and not a
value of some type, say, the integer 7. We can hide this implementation detail by introducing a type
alias (§6.4.2) for Iterator:
template<typename T>
using Iterator = typename T::iterator;
// T’s iterator
template<typename C, typename V>
vector<Iterator<C>> find_all(C& c, V v)
// find all occurrences of v in c
{
...
그것은 일을 더 명확하게하지 않습니다. 나는 그것이 무엇인지 이해 using Iterator = typename T::iterator;
하지만 두 번째 <> 사용법을 설명하지 않습니다.
template<typename C, typename V> //template declaration
vector<typename C::iterator> //return type (vector of iterators)
find_all //function name
(C& c, V v) //argument list
함수 find_all
는 vector<typename C::iterator>
, 또는 "C에 대한 반복자의 벡터"를 반환합니다 .
typename
필요한 이유 는 다음 질문에 설명되어 있습니다. "typename"키워드가 규정 된 독립 이름 앞에가 아니라 규정 된 종속 이름 앞에 필요한 이유는 무엇입니까?
템플릿이없는 더 간단한 예 <>
는 반환 유형 에서도 사용 합니다.
std::vector<int> generateNNumbers(std::size_t numberOfElements)
{
std::vector<int> res;
...
return res;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다