如何调用模板中定义的函数

时间:2014-09-10 17:01:48

标签: c++

我正在尝试为一组x和y数据找到多项式回归。我下载了下面的模板,但我不知道如何调用它,我的尝试遇到错误LNK2019:未解析的外部符号。

#pragma once

#ifdef BOOST_UBLAS_TYPE_CHECK
#   undef BOOST_UBLAS_TYPE_CHECK
#endif
#define BOOST_UBLAS_TYPE_CHECK 0
#ifndef _USE_MATH_DEFINES
#   define _USE_MATH_DEFINES
#endif

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <vector>
#include <stdexcept>

/*
Finds the coefficients of a polynomial p(x) of degree n that fits the data, 
p(x(i)) to y(i), in a least squares sense. The result p is a row vector of 
length n+1 containing the polynomial coefficients in incremental powers.

param:
    oX              x axis values
    oY              y axis values
    nDegree         polynomial degree including the constant

return:
    coefficients of a polynomial starting at the constant coefficient and
    ending with the coefficient of power to nDegree. C++0x-compatible 
    compilers make returning locally created vectors very efficient.

*/
template<typename T>
std::vector<T> polyfit( const std::vector<T>& oX, 
const std::vector<T>& oY, int nDegree )
{
...
}

我不认为你需要模板的其余部分来帮助我,但我会在必要时发布。 (它来自此网站http://vilipetek.com/2013/10/07/polynomial-fitting-in-c-using-boost/)如果有更好/更容易的工具,请告诉我。

这是我尝试运行它的方式: 声明

std::vector<int> polyfit( const std::vector<int> xsplinevector, 
                   const std::vector<int> ysplinevector, 

函数调用

polynomial = polyfit((xsplinevector), (ysplinevector), 4);
               int nDegree );

3 个答案:

答案 0 :(得分:2)

以下是一个例子:

#include <vector>
#include <polyfit.hpp>

int main()
{
    std::vector<int> xsplinevector;
    std::vector<int> ysplinevector;
    std::vector<int> poly;

    // fill both xsplinevector and ysplinevector

    poly = polyfit(xsplinevector, ysplinevector, 4);

}

答案 1 :(得分:0)

您的(显式)函数调用应该是:

polynomial = polyfit<int>((xsplinevector), (ysplinevector), 4);

并且不要使用int模板化类型重新声明该函数,这可能是导致错误的原因。

答案 2 :(得分:0)

由于您按如下方式定义了模板化函数:

template<typename T>
std::vector<T> polyfit( const std::vector<T>& oX, 
const std::vector<T>& oY, int nDegree )
{
...
}

使用它时,模板参数需要出现在函数名后面。对于课程,您可以这样做:

myClass<int> someVariable;

如果是函数,你会这样做:

myFunction<int>();

所以,在你的特定情况下:

vector<int> polynomial;
polynomial = polyfit<int>((xsplinevector), (ysplinevector), 4);