Intro to Templates and Concepts

Interesting. I really like the explanations about Template Overloading and specific ones ++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

template<typename T>
void foo(T t) {
    std::cout << "Generic foo(T t) for " << typeid(t).name() << std::endl;
}

template<typename T>
void foo(T* t) {
    std::cout << "Specific foo(T* t) for " << typeid(t).name() << std::endl;
}

int main()
{
    foo(7);
    foo(1.234567);
    foo((void*)NULL); // clever

    return 0;
}


Generic foo(T t) for int
Generic foo(T t) for double
Specific foo(T* t) for void * __ptr64
Last edited on
May be interesting:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <typeinfo> // The header <typeinfo> must be included before using typeid
                    // (if the header is not included, every use of the keyword typeid makes the program ill-formed.)
                    // https://en.cppreference.com/w/cpp/language/typeid

template<typename T>
void foo(T t) {
    std::cout << "Generic foo(T t) for " << typeid(t).name() << std::endl;
}

template<typename T>
void foo(T* t) {
    std::cout << "Specific foo(T* t) for " << typeid(t).name() << std::endl;
}

int main()
{
    foo( nullptr ) ; // generic with T == std::nullptr_t
    foo( &std::type_info::name ) ; // generic with T == const char* (std::type_info::*)() const 
    // foo( std::cout ) ; // *** error ***
}
Registered users can post here. Sign in or register to post.