考虑如何在 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()
已启用,但首选特定版本,因为 0
是 int
,特定版本会额外收到int
(完全匹配)和泛型附加 long
( int
可转换为 long
但不是完全匹配)。当
A
不支持 check_if_possible()
,只有通用 f_helper()
可用。
关于c++ - 如何使用 sfinae 排除定义了函数的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64896281/