【问题标题】:error: no matching function for call to [...] note: template argument deduction/substitution failed错误:没有匹配的函数调用 [...] 注意:模板参数推导/替换失败
【发布时间】:2015-10-22 13:06:31
【问题描述】:
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:

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

【问题讨论】:

    标签: c++ templates c++11 instantiation


    【解决方案1】:

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

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

    Live example

    【讨论】:

    • 或者,使用模板模板。但是,这仅限于某个签名...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多