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++?
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.
Just use a template specialization.
template <typename T> void foo() { do_something(); }
template<> void foo<int>() { do_something(); do_something_else(); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With