如何检查两个模板参数是否完全相同?

kfm*_*e04 6 c++ templates c++11

如何修改以下函数模板,以便在模板参数TU类型完全相同的情况下返回42 ?

template<typename T,typename U>
int Foo()
{
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 13

使用std::is_same可以提供所需的行为:

#include <type_traits>

template<typename T,typename U>
int Foo()
{
    return std::is_same<T, U>::value ? 42 : 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 但这不是专业化的 (2认同)

Tem*_*Rex 5

一种惯用的方法是将工作委托给detail命名空间中的辅助函数对象,您可以将其部分专门用于与 whereT相同的情况U(或您可以在类模板中使用的任何其他编译时模式)。

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>()();
}
Run Code Online (Sandbox Code Playgroud)

对于也有可推导参数的函数(例如 a will Foo(T x, U y)),这结合了函数模板的参数推导的能力和类模板的专业化能力,而用户不是更聪明的(嗯,你需要他们不调用任何东西的约定从namespace detail直接)