samedi 10 décembre 2022

Dynamic template array in c++ [duplicate]

I'm trying to make universal function for generating a dynamic array with random elements and I want to use template, so I can choose data type whenever I want. The problem is:

LNK2019 unresolved external symbol "public: static double * __cdecl ArrayOperations<double>::GenerateRandomArray(double,double,unsigned int)" (?GenerateRandomArray@?$ArrayOperations@N@@SAPANNNI@Z) referenced in function _main   Algorithms  G:\PrivateRepositories\CppDirectory\Algorithms\Source.obj

my header file:

#include<random>
#include <iostream>

template<class T>
class ArrayOperations
{
public:
    static T* GenerateRandomArray(T, T, size_t);
    //static double* GenerateRandomArray(double, double, size_t);
};

and my source file:

#include "ArrayOperations.h"

template<class T>
T* ArrayOperations<T>::GenerateRandomArray(T a, T b, size_t size){
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(a, b + 1.);

    auto arr = std::make_unique<T>[size];
    for (size_t i = 0; i < size; i++) {
        arr[i] = dist(mt);
    }

    return arr;
}

main function:

int main() {
    const size_t arrSize = 1000;

    auto arr = ArrayOperations<double>::GenerateRandomArray(20.1, 50.5, arrSize);

    for (size_t i = 0; i < arrSize; i++){
        std::cout << arr[i] << ",";
    }
}

I can't find the solution on the internet. Code works well when i remove templates and replace them with eg. int or double.

Aucun commentaire:

Enregistrer un commentaire