如何检查两个模板参数是否完全相同
How to check if two template parameters are exactly the same?
如何
修改以下函数模板,使其在模板参数T
和U
类型完全相同时返回 42?
template<typename T,typename U>
int Foo()
{
return 0;
}
使用 std::is_same
可以提供所需的行为:
#include <type_traits>
template<typename T,typename U>
int Foo()
{
return std::is_same<T, U>::value ? 42 : 0;
}
一种惯用的方法是将工作委托给 detail
命名空间中的帮助程序函数对象,您可以部分专用于T
与 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>()();
}
对于也有可推导参数的函数(例如,Foo(T x, U y)
会),这结合了函数模板的参数推导功能和类模板的专用功能,没有用户都是更聪明的(好吧,你需要约定,他们不会直接从namespace detail
调用任何东西)
为了答案的完整性,以下是在没有类的情况下在编译时做出此选择的方法:
namespace detail
{
int Foo(std::true_type)
{
return 42;
}
int Foo(std::false_type)
{
return 0;
}
}
template <typename T, typename U>
int Foo()
{
return detail::Foo(std::is_same<T, U>());
}
当两个不同的代码路径对参数有不同的要求(但在本例中没有)时,此编译时分支非常重要。例如,在一条路径中使用成员函数x()
,而在另一条路径中使用y()
;或者正如您所指出的,甚至是完全不同的"功能。
对我来说,这比管理一个班级要简单得多。
这个呢?
#include <iostream>
template<typename T,typename U>
struct Foo {
int operator()()
{
return 0;
}
};
template<typename T>
struct Foo<T, T> {
int operator()()
{
return 42;
}
};
int main() {
std::cout << Foo<int, int>()() << std::endl;
std::cout << Foo<int, double>()() << std::endl;
}
相关文章:
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 是否可以对零模板参数进行模板专门化
- 函数作为模板参数,是否对返回类型强制约束
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 函数是否可以访问传递给main()的参数
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 如何检查给定的参数是否为 cv::noArray()?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 如果返回 -1,时间() 的参数是否被修改?
- 用于检查值是否为其任何参数的帮助程序函数
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 模板化检查是否存在带有参数列表的类成员函数?
- 我如何知道作为参数的size_t在函数中是否有效?
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 是否可以在运行时强制转换模板参数?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 编译器是否强制根据模板参数计算表达式?
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?