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.
template<typename T> double foo(vector<T> arr);
The static member is declared or defined inside the template< … > class { … } block. If it is declared but not defined, then there must be another declaration which provides the definition of the member.
The static declaration can be of template argument type or of any defined type. The statement template T K::x defines the static member of class K , while the statement in the main() function assigns a value to the data member for K <int> .
Each instantiation of function template has its own copy of local static variables. For example, in the following program there are two instances: void fun(int ) and void fun(double ). So two copies of static variable i exist. Each instantiation of class template has its own copy of member static variables.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates. C++ template is also known as generic functions or classes which is a very powerful feature in C++.
Define the function in the .h file.
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 ); }
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.
template<typename T> class First { public: static double foo(const vector<T>& arr) {}; };
You can then call the function like:
First<MyClass>::foo(vect);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With