类中的静态模板函数

Cod*_*lus 23 c++ static templates class typename

如何在类中创建以下函数,然后从main访问此函数?我的类只是一堆静态函数的集合.

template<typename T> double foo(vector<T> arr);
Run Code Online (Sandbox Code Playgroud)

Tim*_*hko 32

在.h文件中定义函数.

对我来说很好

啊

#include <vector>
#include <iostream>

using namespace std;
class A {
public:
template< typename T>
    static double foo( vector<T> arr );

};

template< typename T>
double A::foo( vector<T> arr ){ cout << arr[0]; }
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include "a.h"
int main(int argc, char *argv[])
{
    A a;
    vector<int> arr;
    arr.push_back(1);
    A::foo<int> ( arr );
}
Run Code Online (Sandbox Code Playgroud)

 

  • 您不希望在头文件中使用using语句:"using namespace std;" 请改用"std :: vector <T>". (20认同)
  • 每次声明模板时,在头文件中定义它们,然后它就可以了)) (2认同)

Luc*_*ore 7

您创建一个模板类:

template<typename T>
class First
{
public:
    static  double foo(vector<T> arr) {};
};
Run Code Online (Sandbox Code Playgroud)

另请注意,您应该vector通过引用传递,或者在您的情况下,const引用也会执行相同的操作。

template<typename T>
class First
{
public:
    static  double foo(const vector<T>& arr) {};
};
Run Code Online (Sandbox Code Playgroud)

然后您可以像这样调用该函数:

First<MyClass>::foo(vect);
Run Code Online (Sandbox Code Playgroud)

  • 那里有一些不必要的分号。 (2认同)