Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static template functions in a class

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); 
like image 341
CodeKingPlusPlus Avatar asked Feb 19 '12 02:02

CodeKingPlusPlus


People also ask

What happens when there is a static member in a template class function?

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.

Can a static function be template?

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> .

How do you define a static variable for a template class?

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.

Can template be used for class?

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++.


2 Answers

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 ); } 

 

like image 156
Dmitriy Kachko Avatar answered Oct 06 '22 01:10

Dmitriy Kachko


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); 
like image 28
Luchian Grigore Avatar answered Oct 06 '22 01:10

Luchian Grigore