Skip to content

Commit 850e921

Browse files
typename_keyword.cpp
1 parent 19df167 commit 850e921

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

typename_keyword.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#include <iostream>
2+
#include <memory> //std::shared_ptr
3+
4+
/**
5+
this program demos the usage of "typename" keyword
6+
"typename" is needed to be added for qualified name when template argument is unsure
7+
**/
8+
9+
//[C++ Cast Template](https://stackoverflow.com/questions/37983562/c-cast-template)
10+
//[Where and why do I have to put the “template” and “typename” keywords?](https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords)
11+
//[Qualified name lookup](https://en.cppreference.com/w/cpp/language/qualified_lookup)
12+
13+
template<typename T>
14+
class Animal{
15+
public:
16+
using Ptr = std::shared_ptr< Animal< T > >;
17+
};
18+
19+
template<typename T>
20+
void f(){
21+
Animal<T> a;
22+
23+
//error: need ‘typename’ before ‘Animal<T>::Ptr’ because ‘Animal<T>’ is a dependent scope
24+
//error: expected ‘;’ before ‘ap’
25+
//Animal<T>::Ptr ap;
26+
27+
//correct
28+
typename Animal<T>::Ptr ap;
29+
}
30+
31+
int main(){
32+
//ok
33+
Animal<int> a;
34+
//when template argument is concrete, we don't need to add "typename"
35+
Animal<int>::Ptr ap;
36+
return 0;
37+
}

0 commit comments

Comments
 (0)