static template functions in a class

后端 未结 2 876
情深已故
情深已故 2020-12-28 13:54

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.

t         


        
相关标签:
2条回答
  • 2020-12-28 14:13

    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);
    
    0 讨论(0)
  • 2020-12-28 14:30

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

     

    0 讨论(0)
提交回复
热议问题