Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two template parameters are exactly the same?

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;
}
like image 616
kfmfe04 Avatar asked Jan 31 '13 21:01

kfmfe04


2 Answers

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;
}
like image 134
hmjd Avatar answered Sep 28 '22 09:09

hmjd


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)

like image 31
TemplateRex Avatar answered Sep 28 '22 09:09

TemplateRex