c++ - 函数指针的类型特征?
问题描述
我需要有条件地使用模板类std::abs
或std::fabs
模板类,这里是简化版本的相关代码:
template <typename T>
class C
{
public:
using type = std::conditional_t<std::is_integral_v<T>, std::uint64_t, long double>;
using check = std::is_integral<type>;
// ERROR: mismatch in format parameter list
constexpr auto ptr_abs = check::value ? &std::abs<check::value_type> : &std::fabs;
// use pointer
void use_ptr()
{
auto x = (*ptr_abs)(-3);
}
};
没有一个尝试对我有用,我一无所知。
int main()
{
C<int> a;
a.f();
C<float> b;
b.f();
}
解决方案
你真的需要使用函数指针吗?利用 C++ 类型安全机制不是更好吗?如下:
template <typename T>
class C
{
public:
using type = std::conditional_t<std::is_integral_v<T>, std::uint64_t, long double>;
static const bool check = std::is_integral_v<type>;
std::function<type(type)> abs = [](auto arg)
{
if constexpr (check) return std::abs(static_cast<long long>(arg));
else return std::fabs(arg);
};
void use()
{
auto x = abs(-3);
}
};
这对我很有效。请注意,无std::abs
符号整数没有,因此,为了避免歧义,我必须通过强制转换来选择特定的重载(long long
在这个例子中;我不知道是什么Result
)。
在 C++17 之前,没有if constexpr
.
推荐阅读
- liferay-7.2 - Liferay 跨站点复制布局内容类型
- angular - 如何在Angular的一组迭代JSON输出中迭代一个数组?
- concourse - Concourse CI 中的资源类型:如果 Check 总是只返回最新版本会怎样?
- azure - 将模型部署到 Kubernetes
- django - docker 容器上的 Django 在生产服务器中返回 localhost 作为域
- python - Python 将原始 GMT 转换为其他时区,例如 SGT
- html - 极高的元素故障
- mysql - 加载数据本地 INFILE 错误 2068 (HY000)
- here-api - 这里 Map Api 使用 Retrofit 获取调用
- apache-spark - Spark SQL - 默认情况下未启用配置单元