将返回类型推断为模板参数类型方法

deducing return type to be type of template arguments method

本文关键字:参数 类型 方法 返回类型      更新时间:2023-10-16

我很难用英语准确解释我的意思,但以下不可编译的代码可能会说明我所追求的:

template<class T>
auto fn(T t) -> decltype(T::method_call())
{
    return t.method_call();
}

基本上,我希望函数返回 T 的方法返回的任何内容。实现此目的的语法是什么?

在 C++14 中,您可以使用推导的返回类型简单地说:

template <typename T>
decltype(auto) fn(T t) { return t.method_call(); }

您还可以使用尾随返回类型来指定相同的内容:

template <typename T>
auto fn(T t) -> decltype(t.method_call()) { return t.method_call(); }