Search code examples
c++templatesdynamic-memory-allocation

About dynamic array construction in C++


I'm revising my C++ skills for a machine learning project. So, I was working on a dynamically allocating memory functionality. My idea is define such functions as static ones and put them a class and then call them as needed. So I defined following headerfile named Utils.h -

//Utils.h
#include <stdio.h>

class Utils
{
public:
    template<class T> static T* create1DArray(int size);            
};

Then I created following Utils.cpp as -

//Utils.cpp
#include<stdio.h>
#include<malloc.h>
#include"Utils.h"


template<class T> T* Utils::create1DArray(int size)
{
    T* a = new T [size];
    return a;
}

Then I tested them as -

#include<iostream>
#include<conio.h>
#include"Utils.cpp"

using namespace std;
int main()
{
    cout<<"Test";
    double* a;    
    int n=3;
    a = Utils.create1DArray<double>(n);
    getch();
    return 0;   
}

But I got following errors -

error C2275: 'Utils' : illegal use of this type as an expression    
error C2228: left of '.create1DArray' must have class/struct/union  
error C2062: type 'double' unexpected   

But surprisingly when I use this function as a standalone one without putting inside the function it works. Any idea how to solve it?


Solution

  • You are trying to use the . dot notation to invoke a static method.

    Use the :: correct operator instead.

    Utils::create1DArray<double>(n)