C++ 类中的静态模板函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9346076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
static template functions in a class
提问by CodeKingPlusPlus
How do I make the following function inside a class and then access this function from main? My class is just a collection of a bunch of static functions.
如何在类中创建以下函数,然后从 main 访问此函数?我的课程只是一堆静态函数的集合。
template<typename T> double foo(vector<T> arr);
回答by Tim Kachko
Define the function in the .h file.
在 .h 文件中定义函数。
Works fine for me
对我来说很好用
a.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]; }
main.cpp
主程序
#include "a.h"
int main(int argc, char *argv[])
{
A a;
vector<int> arr;
arr.push_back(1);
A::foo<int> ( arr );
}
回答by Luchian Grigore
You make a template class:
你创建一个模板类:
template<typename T>
class First
{
public:
static double foo(vector<T> arr) {};
};
Also note that you should pass vector
by reference, or in your case, also const
reference would do the same.
另请注意,您应该通过vector
引用传递,或者在您的情况下,const
引用也会做同样的事情。
template<typename T>
class First
{
public:
static double foo(const vector<T>& arr) {};
};
You can then call the function like:
然后,您可以调用该函数,如:
First<MyClass>::foo(vect);