【问题标题】:C++11 return type deduction using auto and decltype使用 auto 和 decltype 的 C++11 返回类型推导
【发布时间】:2018-03-10 16:17:48
【问题描述】:

我正在尝试编写一个将向量与标量值相乘的函数。 我想返回一个数据类型最高的 Vector。

当我编译下面的代码时,我得到的错误是 “错误:decltype 的参数必须是表达式”

我该如何解决这个问题?

template<typename T>
class Vector {
private:
    T* data;
    int length;

    template <typename S>
    auto operator*(S scalar) const /
    -> decltype(Vector<typename std::common_type<S,T>::type>);
    {
        // Function Logic
    }
}

【问题讨论】:

  • 只需删除decltypeVector&lt;typename std::common_type&lt;S,T&gt;::type&gt; 已经是你想要的类型了吧?

标签: c++ c++11 templates decltype


【解决方案1】:

decltype 用于确定表达式的类型。 Vector&lt;typename std::common_type&lt;S, T&gt;::type&gt; 已经是一种类型。所以没有什么可以使用decltype on。

另外,这不是返回类型推导。它只是一个后期指定的返回类型,在这种情况下是不必要的,因为返回类型不依赖于任何参数名称。你可以很容易地做到这一点:

template<typename S>
Vector<typename std::common_type<S,T>::type operator*(S scalar) const

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多