c++ - 错误 : no matching function for call to [. ..] 注意:模板参数推导/替换失败

标签 c++ templates c++11 instantiation

template <int dim = 2>
class point {
private:
    std::array<double, dim> coords;
public:
    /* Constructors, destructor, some members [...] */
    template <typename operation_aux, int dim_aux> point<dim_aux>
        plus_minus_helper(const point<dim_aux>& op1, const point<dim_aux>& op2);
};

template <typename operation, int dim> point<dim>
    plus_minus_helper(const point<dim>& op1, const point<dim>& op2)
{
    /* Do all the calculations.
     * The algorithm is very similar for both addition and subtraction,
     * so I'd like to write it once
     */
}

template <int dim>
    point<dim> operator+(const point<dim>& op1, const point<dim>& op2)
{
    return plus_minus_helper<std::plus>(op1, op2);
}

template <int dim>
    point<dim> operator-(const point<dim>& op1, const point<dim>& op2)
{
    return plus_minus_helper<std::minus>(op1, op2);
}

int main(int argc, char * argv []) {
    point<2> Pt1(1, 2), Pt2(1, 7), Pt3(0, 0);

    Pt3 = Pt1 + Pt2;
    std::cout << Pt3(0) << " " << Pt3(1) << std::endl;
}

在 GCC 上编译此代码会产生以下错误

./test.cpp: In instantiation of ‘point<dim> operator+(const point<dim>&, const point<dim>&) [with int dim = 2]’:
./test.cpp:47:17:   required from here
./test.cpp:35:49: error: no matching function for call to ‘plus_minus_helper(const point<2>&, const point<2>&)’
     return plus_minus_helper<std::plus>(op1, op2);
                                                 ^
./test.cpp:35:49: note: candidate is:
./test.cpp:26:5: note: template<class operation, int dim> point<dim> plus_minus_helper(const point<dim>&, const point<dim>&)
     plus_minus_helper(const point<dim>& op1, const point<dim>& op2)
     ^
./test.cpp:26:5: note:   template argument deduction/substitution failed:

看起来是模板初始化的问题,实际上-操作符并没有报错。 我提供了所有必要的类型来实例化函数、操作和运算符的维度。尺寸隐含在参数中,我不认为我传递了冲突的参数。
我正在尝试调用传递给它的辅助函数来执行计算(加法或减法)。我不想将算法写两次,一次用于加法,一次用于减法,因为它们仅在执行的操作上有所不同。
如何修复此错误?

最佳答案

问题是,std::plus/std::minus是模板类。你应该指出,你想发送哪个类的实例化,或者你是否可以使用 C++14 - 只是 <> ,如果你不想指出,哪个实例化编译器应该使用你可以使用 template template parameter .

return plus_minus_helper<std::plus<>>(op1, op2);

Live example

关于c++ - 错误 : no matching function for call to [. ..] 注意:模板参数推导/替换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33281774/

相关文章:

c++ - 如何通过引用为 C++0x 传递 Lambda 表达式参数

c++ - 什么时候使用抽象类有意义

c++ - 没有匹配的构造函数来初始化模板类的构造函数

C++ 模板和别名

c++ - 从 std::tuple of double 的 std::vector 读取线程安全?

c++ - 使用 typedef 将多个模板类合并为一个类

c++ - 模板重载 ostream 运算符

c++ - 从两个 'interfaces' 实现相同的方法签名

c++ - 如何打印目录树?

javascript - 是否有支持递归之类的javascript模板引擎?