C++ - 一个语法问题

  我琢磨着如何才能实现传入函数类型参数的可变参。

  比如,我最开始这样子想的:

#include <iostream>
#include <cmath>
#include <functional>
#include <algorithm>


template<class FT, class ...Args>
double PenaltyFunction(double x0, double y0, double r0, FT _FuncType, Args ... r)
{
    return r0 * _FuncType(x0, y0) + PenaltyFunction(r...);
}

int main()
{
    double x1 = 1., x2 = 0.;
    std::cout << PenaltyFunction(
        x1, x2, 1., [](double x1, double x2) { return x1 * x1 + x2 * x2; },
        x1, x2, -1., [](double x1, double x2) { return std::log(x1 - 1); } // 多个类似的函数传递
    );

    return 0;
}

  但得到 MSVC 编译错误:

错误	C2672	“PenaltyFunction”: 未找到匹配的重载函数	aaaa	D:\source\repos\aaaa\aaaa\aaaa.cpp	10	
错误	C2780	“double PenaltyFunction(double,double,double,FT,Args...)”: 应输入 5 个参数,却提供了 0 个	aaaa	D:\source\repos\aaaa\aaaa\aaaa.cpp	8	

  之后就是改来改去都不对,然后发现似乎是因为函数类型参数不能可变参,百度、谷歌了一会儿都没找到类似的问题。当然我不想用函数指针,也没测试过,主要想用的是 C++ 的可变参模板。

  

猜你喜欢

转载自www.cnblogs.com/darkchii/p/12662126.html