Is there a way how to create template function with no input parameters like in C++?

Viewed 92

I am new to julia (just started couple of days ago). I would like to ask, if is there a way of defining the template function in julia with no input parameters similiar to this in C++.

#include <iostream>
#include <iomanip>
#include <type_traits>
#include <cstdint>

template<typename eT>
eT fun()
{
    eT x;
    
    if (std::is_same<eT,double>::value)
    {
        std::cout << "returns double\n";
    } else if ( std::is_same<eT,int>::value ) {
        std::cout << "returns int\n";
    } else {
        std::cout << "...\n";
    }
    
    return static_cast<eT>(1.000);
}


int main()
{
    int i = fun<int>();
    double d = fun<double>();

    return 0;
}

So, the question is how Can i Do it properly in Julia.

function test_template() where (T<:Real)
    x::T = round( T , 1.0)

    if x isa Float64
        println("Data type is Float64")
    elseif x isa Float32
        println("Data type is Float32")
    elseif x isa Int64
        println("Data type is Int64")
    else
        println("Data type is unknown")
    end

    return x
end
        

Because, when I call it this way I get

julia> test_template()
ERROR: UndefVarError: T not defined

Thanks you all for sharing your knowledge.

3 Answers

The following definitions:

test_template(::Type{Float64}) = 1.0
test_templete(::Type{Int64}) = 1
test_template(t::DataType) = one(t)

seem close to request. Also checking the generated code for Float64, for example, shows no overhead checking, as it is determined in compile-time (like the C++ template I suppose).

To see the generated code, you can use @code_llvm (and friend macros):

julia> @code_llvm test_template(Int64)
;  @ REPL[3]:1 within `test_template'
define i64 @julia_test_template_277() {
top:
  ret i64 1
}

Tested on Julia 1.6.3

This is similar to comment by @DNF

While the correct solution has been suggested by Dan Getz, you could still possibly write a code that resembled more the one in C (although it is not Julian in style as it defines constructor for wrong type - still it works and shows the flexibility you have with Julia):

struct tmplt{T} end

tmplt{T}() where T <: Real = one(T)

And now:

julia> tmplt{Int}()
1

julia> tmplt{Float64}()
1.0
one(x)

should give you a numeric 1 of a type the same as your input x. if you want to build a function using templating (not needed here) you can use

fun(x::T) where T <: Real = T(1)
Related