gpt4 book ai didi

c++ - 本地类和函数模板

转载 作者:太空宇宙 更新时间:2023-11-04 12:11:02 25 4
gpt4 key购买 nike

我试图使用本地类来模拟本地函数。本地类定义了几个静态辅助函数,其中每个静态函数都需要访问函数作用域中定义的静态数组。这件事适用于普通功能,但在使用模板功能时出现链接错误。代码是:

#include <iostream>

double test_local (double x)
{
static const double coeff[3]={ 0, 1, 2 };

struct local_functions
{
static double f0 (double x)
{
static const double c0=coeff[0]+coeff[1];
return c0+x;
}

static double f1 (double x)
{
static const double c1=coeff[1]+coeff[2];
return c1+x;
}

static double f2 (double x)
{
static const double c2=coeff[2]+coeff[0];
return c2+x;
}
};

return local_functions::f0(x)+local_functions::f1(x)+local_functions::f2(x);
}

template<class t>
t test_local_tmpl (t x)
{
static const t coeff[3]={ 0, 1, 2 };

struct local_functions
{
static t f0 (double x)
{
static const t c0=coeff[0]+coeff[1];
return c0+x;
}

static t f1 (t x)
{
static const t c1=coeff[1]+coeff[2];
return c1+x;
}

static t f2 (t x)
{
static const t c2=coeff[2]+coeff[0];
return c2+x;
}
};

return local_functions::f0(x)+local_functions::f1(x)+local_functions::f2(x);
}

int main (int argc, char** argv)
{
double result=test_local (1e0);

// uncommenting next line generates a linking error
// double result_tmpl=test_local_tmpl (1e0);

std::cout << result << std::endl;
return 0;
}

非模板函数工作正常(它打印 9),而如果我尝试调用模板版本,它编译正常但不在 g++-4.6 下链接:

g++ -c -g local_class.cpp && g++ local_class.o -o local_class
Undefined symbols:
"coeff", referenced from:
double test_local_tmpl<double>(double)::local_functions::f2(double) in local_class.o
double test_local_tmpl<double>(double)::local_functions::f2(double) in local_class.o
double test_local_tmpl<double>(double)::local_functions::f1(double) in local_class.o
double test_local_tmpl<double>(double)::local_functions::f1(double) in local_class.o
double test_local_tmpl<double>(double)::local_functions::f0(double) in local_class.o
double test_local_tmpl<double>(double)::local_functions::f0(double) in local_class.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

这是预期的行为吗,我错过了什么?

最佳答案

这是一个 GCC 错误。您的代码中没有错误。请提交错误报告。

关于c++ - 本地类和函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9842341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com