【发布时间】:2016-09-28 06:31:06
【问题描述】:
考虑以下代码:
auto f() -> decltype(auto) { /* do whatever you want here */ }
int main() { f(); }
推导出返回类型,decltype(auto) 用作尾随返回类型。
下面的代码是稍作修改(实际上是sfinae'd)的版本:
struct S { static void f() {} };
struct T {};
template<typename U>
auto f(int) -> decltype(U::f(), void()) {
// do whatever you want here
}
template<typename>
auto f(char) -> decltype(auto) {
// do whatever you want here
}
int main() {
f<S>(0);
f<T>(0);
}
如果你参加考试这个功能:
template<typename U>
auto f(int) -> decltype(U::f(), void()) {
// do whatever you want here
}
问题是:是否可以使用尾随返回类型进行 sfinae 并且仍然推导出返回类型?
我的意思是类似于下面的代码(当然,这是行不通的):
template<typename U>
auto f(int) -> decltype(U::f(), auto) {
// do whatever you want here
}
注意:我不是在寻找涉及模板参数的替代方法,我知道它们,我只是想知道 this 是否是一个可行的解决方案。
【问题讨论】:
-
不认为这是可能的,但您是否希望将类型推断为
auto或decltype(auto)? -
别以为你可以在这里做任何事。推导的返回类型故意不 SFINAE。
-
@Holt 好问题,我会像第一个例子一样说
decltype(auto),但如果你知道如何将它推导出为auto,它也是一个很好的答案。跨度>
标签: c++ templates language-lawyer sfinae decltype