Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ compile-time type comparsion

Tags:

c++

Consider the function foo.

template <typename T>
void foo() {
    do_something();
    if (T == int) {
        do_somehting_else();
    }
}

In other words, I want it to do_something() and then, if the type is int, do_something_else()

Of course if (T == int) { won't compile. Still: is there any way to compare types in compile-time in C++?

like image 713
DLunin Avatar asked Aug 30 '26 19:08

DLunin


2 Answers

You can use

#include <type_traits>

// ...

template <typename T>
void foo() {
    do_something();
    if (std::is_same<T,int>::value) {
        do_somehting_else();
    }
}

You can learn more about type traits here.

like image 169
Daniel Frey Avatar answered Sep 02 '26 11:09

Daniel Frey


Just use a template specialization.

template <typename T> void foo() { do_something(); }

template<> void foo<int>() { do_something(); do_something_else(); };
like image 28
Basile Starynkevitch Avatar answered Sep 02 '26 10:09

Basile Starynkevitch