我正在编写一个示例程序,以帮助建立对C 模板的理解。我正在尝试使用模板类具有多个功能。
以下是我写过的以下代码。
// Example program
#include <iostream>
#include <string>
using namespace std;
template<class test>
test addstuff(test a, test b){
return a+b;
}
test multiplystuff(test a,test b){
return a*b;
}
int main()
{
double a,b,c;
cout << "Enter a value for a." << endl;
cin >> a;
cout << "Enter a value for a." << endl;
cin >> b;
c = addstuff(a,b);
cout << c << endl;
c = multiplystuff(a,b);
cout << c << endl;
}
我遇到的错误是在我的功能中的测试multiplystuff
中,不在范围内是我收到的错误。我希望模板能够处理多个功能,问题可能是什么?
this:
// ...
test multiplystuff(test a,test b){
return a*b;
}
// ...
这看起来像功能模板吗?对于编译器而言,不是。即使对于人类,如果我认为我希望它不是函数模板。
现在让我们再次添加上下文:
template<class test> // has template parameters
test addstuff(test a, test b) {
return a + b;
}
// no template parameters
test multiplystuff(test a,test b) { // cannot access test?
return a * b;
}
一个函数是一个模板,但第二个功能显然不是。
期望test
在第二个功能中可用,就像期望其他功能可以访问参数:
// has int parameter
void func1(int a) { /* ... */ }
// no int parameter
void func2() {
// cannot access a
}
在此示例中,a
在func2
中不范围。
您的功能模板也会发生同样的事情。模板参数在函数之外不可用。
显然,解决方案是将丢失的参数添加到第二个函数中。
您实际上根本没有模板类。您有2个无关的免费功能addstuff
和multiplystuff
,而template<class test>
仅适用于第一个。实际上使用类或添加另一个template<class test>
:
template<class test>
test addstuff(test a, test b)
{
return a + b;
}
template<class test>
test multiplystuff(test a,test b)
{
return a * b;
}
另外,不要using namespace std;
template<class test>
不是模板声明。它也不声明类(或类模板)。它形成了模板声明的部分部分(在这种情况下。它也可以构成定义的一部分)。
而不是
template<class test>
test addstuff(test a, test b){
return a+b;
}
是模板声明, template<class test> test addstuff(test a, test b);
。
如果您希望addstuff
和multiplystuff
都是模板,则必须将它们声明为模板。但是,我只会使用+
和*
。