Reputation: 1070
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++?
Upvotes: 2
Views: 134
Reputation: 1
Just use a template specialization.
template <typename T> void foo() { do_something(); }
template<> void foo<int>() { do_something(); do_something_else(); };
Upvotes: 5
Reputation: 56921
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.
Upvotes: 5