DO模板声明仅适用于以前立即声明的功能
Do template declarations only work for the function they are immediately declared before
我正在编写一个示例程序,以帮助建立对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
都是模板,则必须将它们声明为模板。但是,我只会使用+
和*
。
相关文章:
- 对可变参数使用声明.如何选择正确的功能
- 在气泡排序程序中未声明错误功能
- 引用 using 声明引入的功能的句子是什么意思?
- 朋友功能声明中的错误C
- 抽象类 A 由类 C 继承"through"类 B "intermediary"。如何声明虚拟功能?
- 如何实现声明功能-C 11,编译时间
- 如何使用C 中的元编程声明多功能
- 如何声明功能接受rvalue的任意长度阵列
- C |声明类外部功能
- 您可以声明会员功能并使他们做不同的事情吗?
- Forward宣布了Singleton班级,并带有Freshial声明的朋友功能
- 打印功能的地址..声明
- 如何将指针声明以在类初始化器中的成员功能并拨打这些指针
- 功能未在范围(GLFW,OpenGL,Slackware)中声明
- C 1Z标准如何定义模板功能声明中属性的正确位置
- 从模板参数中声明功能指针中的模板类中
- 在C 中多次声明功能和变量
- 没有模板就无法声明C 功能
- 在定义模板后声明功能
- 如何声明功能向量(lambdas)