根据类型特征更改函数定义?

change function defination based on type trait?

本文关键字:函数 定义 类型 特征      更新时间:2023-10-16

我想使用enable_if_t根据类型更改我的函数定义。一些类似的东西:

#include<type_traits>
template<typename T> struct A;
template<typename T>
struct A{
std::enable_if_t<std::is_arithmetic<T>::value, bool>
test()
{
return true;
}
std::enable_if_t<!std::is_arithmetic<T>::value,  bool>
test()
{
return false;    
}
};

目前它根本无法编译。

你可以试试

template <typename U = T>
std::enable_if_t<std::is_arithmetic<U>::value, bool>
test()
{ return true; }
template <typename U = T>
std::enable_if_t<!std::is_arithmetic<U>::value,  bool>
test()
{ return false; }

我的意思是。。。SFINAE 适用于函数/方法的模板参数,而不是包含方法的类的模板参数。

使用typename U = T,可以转换T类模板参数,在U中,方法模板参数。