错误:没有用于调用[...]注释的匹配函数:模板参数推断/替换失败

时间:2015-10-22 13:06:32

标签: 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:

似乎模板的instatiaton存在问题,实际上-运算符不会产生任何错误。 我提供了所有必要的类型来实例化函数,操作和操作符的维度。维度隐含在参数中,我不认为我传递了冲突的参数 我试图调用辅助函数传递给它的计算(加法或减法)。我不想一次两次编写算法用于加法,一次用于减法,因为它们仅对执行的操作有所不同。
如何解决此错误?

1 个答案:

答案 0 :(得分:2)

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

template template parameter

Live example