我正在编写一个示例程序来帮助加深对 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
中,它不在范围内是我收到的错误。我希望模板能够处理不止一种功能,问题是什么?
最佳答案
这个:
// ...
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
的范围。
您的函数模板也会发生同样的事情。模板参数在函数外不可用。
显然,解决方案是将缺少的参数添加到第二个函数。
关于c++ - 模板声明是否仅适用于它们之前立即声明的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55005826/