How do I modify the following function template so that it returns 42 if template parameters T
and U
are exactly the same type?
template<typename T,typename U>
int Foo()
{
return 0;
}
Using std::is_same
can provide the desired behaviour:
#include <type_traits>
template<typename T,typename U>
int Foo()
{
return std::is_same<T, U>::value ? 42 : 0;
}
An idiomatic way is to delegate the work to a helper function object in a detail
namespace that you can partially specialize for the case where T
is the same as U
(or for any other compile-time pattern that you can use in class templates).
namespace detail {
template<typename T, typename U>
struct foo
{
int operator()() const
{
return 0;
}
};
template<typename T>
struct foo<T, T>
{
int operator()() const
{
return 42;
}
};
} // namespace detail
template<typename T, typename U>
int Foo()
{
return detail::foo<T, U>()();
}
For functions which also have deducible arguments (e.g. a Foo(T x, U y)
would) this combines the power of argument deduction of function templates, and the specialization capabilities of class templates, without users every being the wiser (well, you need the convention that they do not call anything from namespace detail
directly)
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