You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义可调用类模板中使用decltype(auto)作为返回类型的可行性

关于自定义Callable类模板中使用decltype(auto)的疑问

我正在实现一个简化std::function行为的自定义可调用类模板,尝试用decltype(auto)来让调用可调用对象时保留其精确返回类型(包括const、引用等限定符)。以下是这个类的简化版本:

附言:C++标准中的std::function在调用运算符中使用的是R而非decltype(auto)。

我想了解是否可以通过decltype(auto)达到和R相同的效果。

template <typename>
class Callable;

template <typename R, typename... Args>
class Callable<R(Args...)>
{
public:
    template<typename F>
    Callable(F&& f) : func(std::forward<F>(f)) {}

    decltype(auto) operator()(Args... args) {
        return func(std::forward<Args>(args)...);
    }

private:
    std::decay_t<R(Args...)> func;
};

内容的提问来源于stack exchange,提问作者sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 06:35:54