gpt4 book ai didi

c++ - std::enable_if 和 std::is_arithmetic 作为模板参数的问题

转载 作者:太空狗 更新时间:2023-10-29 19:56:17 25 4
gpt4 key购买 nike

我正在尝试实现一个 OutputArchive 模板类,它有一个模板化函数 processImpl()。看起来像这样:

template<typename ArchiveType>
class OutputArchive {
...

template<typename Type, typename std::enable_if_t<std::is_arithmetic_v<Type>>> inline
ArchiveType& processImpl(Type&& type) {
// Implementation
}

template<typename Type, typename = void> inline
ArchiveType& processImpl(Type&& type) {
// Implementation
}
}

这里的想法是,如果我将 charintfloat 等传递给我的 processImpl() 函数,应该使用第一个重载;然而,事实并非如此。第二个过载似乎总是被使用,我完全不知道我可能做错了什么。我想这确实与我使用 std::enable_if 的方式有关

最佳答案

因此,为了使其正常工作,您应该在两种情况下使用 std::enable_if。我将展示返回类型的示例,但使用模板参数也可以。

template<typename Type> inline
typename std::enable_if_t<std::is_arithmetic_v<Type>, ArchiveType&> processImpl(Type&& type) {
// Implementation
}

template<typename Type> inline
typename std::enable_if_t<!std::is_arithmetic_v<Type>, ArchiveType&> processImpl(Type&& type) {
// Implementation
}

注意第二种情况下的否定。

但是从 C++17 开始,更好的方法是使用 constexpr:

ArchiveType& processImpl(Type&& type) {
if constexpr(std::is_arithmetic_v<type>) {
// implementation
} else {
// implementation
}
}

关于c++ - std::enable_if 和 std::is_arithmetic 作为模板参数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52797598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com