c++ - 编译模板函数时形式参数列表不匹配

标签 c++ template-specialization function-templates

我在编译模板函数时遇到编译时错误,错误是:

error C2563 : mismatch in formal parameter list

无法弄清楚问题出在哪里,编译器没有说明太多问题,您知道问题出在哪里吗?

#include <cmath>    // temporary
#include <iostream>
#include <cassert>

namespace math
{
    //
    // Power function
    //
    template<typename Exp>
    double pow(double base, Exp exponent)
    {
        assert(!(base == 0 && exp <= 0));

        if (base == 0)
            return 0;

        if (exponent == 0 || base == 1)
            return 1;

        if (exponent == 1)
            return base;

        if (exponent < 0)
            return 1 / pow(base, -exponent);

        return base * pow(base, exponent - 1);
    }

    //
    // Power specialization for real exponents
    //
    template<>
    double pow(double base, double exponent)
    {
        // TODO: handle real negative exponents
        return exp(exponent * log(base));
    }
}

int main()
{
    // error C2563:  mismatch in formal parameter list
    std::cout << "pow" << std::endl;
    std::cout << math::pow(1, 2) << std::endl;
    std::cout << math::pow(0, 2) << std::endl;
    std::cout << math::pow(2, 0) << std::endl;
    std::cout << math::pow(3, -4) << std::endl;

    return 0;
}

最佳答案

我想我应该写一个答案给别人看。

在 Martin Morterol 撰写的评论中,他解释了为什么会出现错误。

您正在将 exp 函数与 0 进行比较。 assert(!(base == 0 && exp <= 0));

我假设您想针对负指数断言,所以我已经替换了 exp 和指数,并根据假设输出正确的数据。

Exp 是 cmath header 中可用的函数,它返回 x 的以 e 为底的指数函数,即 e 的 x 次幂:ex。

至于为什么 GCC 编译,它似乎完全忽略了 assert 行,如果我们查看汇编,就可以在 godbolt 上看到这一点

https://godbolt.org/z/BZIw8z

如果我们用 static_assert 替换 assert,gcc 会给出与 clang 相同的错误

https://godbolt.org/z/UpQ6Ks

关于c++ - 编译模板函数时形式参数列表不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56685768/

相关文章:

c++ - 我的应用程序在使用 Do/While 循环解析表时崩溃

c++ - 使用工厂 friend 类来分配新类,好的做法?

c++ - gcc的模棱两可的模板实例化错误

C++:处理整数和字符串的函数模板

c++ - 除了检查发出的机器代码之外,我如何找到 C++ 编译器如何实现某些东西?

c++ - VC++编译器升级2010->2015重新定义; 'constexpr' 说明符不匹配

c++ - 不完整类型的无效使用 (SFINAE)

c++ - 为什么我不能在 std::transform 中使用 std::get<0>?

c++ - 将 std::enable_if 从参数移动到模板参数

C++ - 两个类相互实例化,不能使用前向声明