Create and call a c++ template function

Asked

Viewed 25 times

-1

I have this template below, and when I try to call with the excerpt below, it can’t find the reference

template<typename T> double power(T base, T power) {
    double result = base;
    int j = 0;
    do {
        result *= base;
        j++;
    } while (j < (power - 1));

    return result;
}

And that’s the call:

test_log << "Expected: 27 | Output: " << power(3, 3) << endl; //Expected: 27
test_log << "Expected: 81 | Output: " << power(9, 0.5) << endl; //Expected: 81

The template is in a namespace, but I put "using namespace smath" at the beginning of the call file.

I’m using Mingw on Windows 10 20h2 with Clion 2021.1

1 answer

0


To call a function with template does so: Example:

//Esse é um método de minha API
template <typename in, typename out> out casterBasicVar(in _value){
     out output;
     std::istringstream(_value) >> output;
     return output;
}

This method converts the variables of C++, it is part of a namespace ieirf, to call, similar to his:

int main(){

    int v1;
    string v2 = "5896";

    v1 = ieirf::casterBasicVar<string, int>(v2); //Você coloca o template de acordo com o retorno
    //Se você colocar um template para receber double. Escreva <double, double> ou número similar.
    cout << v1 << "\n\n"; //Imprima 5896

}

Follow this example from my API function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.