c++ - 如何使用 sfinae 排除定义了函数的类型?

标签 c++ sfinae decltype trailing-return-type

考虑如何在 decltype() 中使用逗号表达式尾随返回类型可用于检查是否可以应用函数:

template <class A>
auto f(A a) -> decltype(check_if_possible(a), return_type(a))
如何否定逗号前的部分以排除 check_if_possible(a) 的情况被定义为?
语境:f()是不同 A 的重载函数.我想解决两个实现之间的歧义重载。其中之一使用 check_if_possible(a) ,其他适用于不能应用于 a 的情况.
编辑:
使用 std::enable_if和相关的东西也是受欢迎的,但我想避免额外的辅助函数/模板,因为有几个类似于 f() 的函数。具有不同的启用条件。
如果这是不可能的,那么这也是一个答案;)

最佳答案

How can I negate the part before the comma to exclude cases in which check_if_possible(a) is defined?


我不知道有什么办法,但是...

Context: f is an overloaded function for different A. I want to resolve an ambiguous overload between two implementations. One of them uses check_if_possible(a), the other works in cases where this cannot be applied to a.


我通常写一个f()需要几个 f_helper() 的两种情况的函数接收额外参数的函数。
例如
template <typename A>
auto f (A && a)
 { return f_helper(std::forward<A>(a), 0); }
观察最后一个参数:0 ,这是一个 int然后你可以写check_if_possible()版本,接收额外的 int
template <typename A>
auto f_helper (A a, int) -> decltype(check_if_possible(a), return_type(a))
 { /* ... */ }
和一个通用版本,始终启用,接收额外的 long
template <typename A>
auto f_helper (A a, long)
 { /* ... */ }
这样,当 A支持 check_if_possible() , 两者 f_helper()已启用,但首选特定版本,因为 0int ,特定版本会额外收到int (完全匹配)和泛型附加 long ( int 可转换为 long 但不是完全匹配)。
A不支持 check_if_possible() ,只有通用 f_helper()可用。

关于c++ - 如何使用 sfinae 排除定义了函数的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64896281/

相关文章:

android - QML 设备部署

c++ - 可以将 C++ 单元测试集成到 Xcode 的 XCTest 中吗?

c++ - * 是 C++ 函数名吗?

c++ - decltype(1, t) 应该是左值引用吗? (编译器不同意)

c++ - boost::static_visitor 未能专门化具有多种不同可能类型的函数模板

c++ - Qmake给我错误

c++ - 为什么 SFINAE 不能跨多重继承工作?

使用 decltype 和 constness 的 C++11 尾随返回成员函数

c++ - 在不使用 decltype[c++] 的情况下传递键类型的比较函数

c++ - 如何使用decltype获取没有引用的指针?