【问题标题】:how to declare member function using template? (not template class)如何使用模板声明成员函数? (不是模板类)
【发布时间】:2019-11-30 08:12:40
【问题描述】:

我想在类中声明一个模板成员函数。 据我所知,我们可以在 case1 下声明。 但它会做几个类,但我只想做一个类。 我不会使用模板来设置成员变量。我只会将它用于成员函数的参数。我想制作可以在一个类实例中处理不同类型的模板函数。 那么,有没有办法在一个类中制作模板功能?

//case1, standard template function
#include <iostream>
using namespace std;

template <typename T>
class A{
     public:
       void f(T n){
         cout << n <<endl;
       }
};

int main(){
    A<int> a1;
    a1.f(1);
    A<float> a2;
    a2.f(0.1);
}

//case2, i want to make member function which can receive vary type.
#include <iostream>
using namespace std;

class A{
      public:
        template <typename T>
        void f(T n){
           cout << n <<endl;
        }
}

int main(){
   A a();
   a.f(1);
   a.f(0.1);
}

【问题讨论】:

  • 这个A a();是函数声明(阅读更多关于c++中的most vexing parse),你想要A a;
  • 你试过了吗?你遇到了什么问题?
  • 抱歉造成混淆。看起来对构造函数而不是模板存在一些误解。谢谢

标签: c++ class templates


【解决方案1】:

在修正了几个小错别字后,您的代码对我有用:

#include <iostream>
using namespace std;

class A{
      public:
        template <typename T>
        void f(T n){
           cout << n <<endl;
        }
};

int main(){
   A a;
   a.f(1);
   a.f(0.1);
}

$ g++ main.cc

./a.out

1

0.1

【讨论】:

  • 抱歉造成混淆。看起来对构造函数而不是模板存在一些误解。谢谢
猜你喜欢
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
相关资源
最近更新 更多