-1

我的目标是让非成员函数使用模板作为返回值。这样我就可以返回一个浮点数组、一个双精度数组等。我得到一个“无法推断模板参数'T'”错误。

这是我尝试使用的方法:

template<typename T>
T* make(double magnitude, double frequency, double radians, double seconds,
        int samplesPerSecond) {
    long samples = length(seconds, samplesPerSecond);
    T *wave = new T[samples];
    for (int i = 0; i < samples; i++) {
        wave[i] = magnitude
                * sin(
                        (2.0 * (M_PI) * frequency * i / samplesPerSecond)
                                + radians);
    }
    return wave;
}

我首先尝试正常调用该方法。

double *ds = make(magnitude, frequency, radians, seconds, samplesPerSecond);

我尝试在函数名之后添加类型名。

double *ds = make<double>(magnitude, frequency, radians, seconds, samplesPerSecond);

我查看了网络上的几个页面,到目前为止它们都涵盖了成员函数,并解释了不能从返回类型推导出类型,那么你如何告诉编译器类型呢?

4

2 回答 2

2

您可以使用非成员函数执行此操作如下例所示,它将模板化类型的两个值相加:

#include <iostream>

template<typename T> T add(const T &val1, const T &val2) {
    return val1 + val2;
}

int main() {
    auto eleven = add<int>(4, 7);
    std::cout << "4   + 7   = " << eleven << '\n';
    auto threePointFour = add<double>(1.1, 2.3);
    std::cout << "1.1 + 2.3 =  " << threePointFour << '\n';
}

正如预期的那样,该代码的输出是:

4   + 7   = 11
1.1 + 2.3 =  3.4

您的案例可能不起作用,因为模板化函数的定义可能不正确 - 因为您没有提供,所以很难确定。因此,您可能想看看它与我自己的add函数相比如何,如上所示。


顺便说一句(因为您的标题表明这可能是您正在尝试的),您也可以在使用参数列表中的模板类型(仅返回类型)的情况下执行此操作:

#include <iostream>

template<typename T> T addAndHalve(const double &val1, const double &val2) {
    auto x = (val1 + val2) / 2;
    std::cout << "debug " << x << ": ";
    return x;
}

int main() {
    auto eleven = addAndHalve<int>(4, 7);
    std::cout << "(4   + 7  ) / 2 = " << eleven << '\n';
    auto threePointFour = addAndHalve<double>(1.1, 2.3);
    std::cout << "(1.1 + 2.3) / 2 =  " << threePointFour << '\n';
}

您可以看到这仅影响返回值,double用于所有参数:

debug 5.5: (4   + 7  ) / 2 = 5
debug 1.7: (1.1 + 2.3) / 2 =  1.7
于 2020-07-01T00:16:57.833 回答
0

我注意到 c++ 标准库有像 lround() 这样的函数,其中 l 表示函数返回一个 long,所以我最终也创建了多个方法。

int16_t* makei(double magnitude, double frequency, double radians,
        double seconds, int samplesPerSecond);
float* makef(double magnitude, double frequency, double radians, double seconds,
        int samplesPerSecond);

这违反了我经常听到的“避免不必要的重载”规则,下面的代码确实有效。

double *ds = make<double>(magnitude, frequency, radians, seconds, samplesPerSecond);

我有另一个未知错误阻止它工作。

于 2020-07-01T14:07:03.137 回答