c++ - 模板声明是否仅适用于它们之前立即声明的函数

标签 c++ templates

我正在编写一个示例程序来帮助加深对 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/

相关文章:

C++:静态指针、静态对象和动态内存分配

c++ - 有没有办法将多个枚举合并为一个?

c++ - 具有模板功能的跨平台类

c++ - 根据 C++ 中的外部输入选择类

c++ - C++模板将如何处理溢出?

c++ - cl.exe 编译器显然接受了不正确的 C++ 代码

c++ - 在 C++ 中运行经过训练的 tensorflow 模型

c++ - 在 C++ 函数调用中使用自增运算符是否合法?

c++ - 返回嵌套模板的模板方法的签名会产生编译错误

c++ - 将从一个函数返回的 vector 传递给另一个函数