Ephedo
Ephedo

Reputation: 83

Templates; constexpr ; compile time

I have several questions

1)

#include <iostream>
template<typename T>
void func(T t){}


int main()
{
 int i;
 double d;
 std::cin>>i;

if(i==1)
 func(i);
else
 func(d);
}

When (runtime/compile time) does one generate needed function? How many versions of functions are after instantiation?

2)What`s the difference between

template<typename T> auto func(T t){return 0;}

and

template<typename T> constexpr auto func(T t){return 0;}

As i understand template works at compile time and constexpr too. Why(and when) do i need to use constexpr with templates?

Upvotes: 7

Views: 19360

Answers (1)

Manish Baphna
Manish Baphna

Reputation: 432

Answer(1): Two versions.

Answer(2): Function instantiation and execution are two different concepts. template function is instantiated at compile time, that doesn't mean it will execute compile time. constexpr is different in this context as it, depending on the context where it's called and arguments, it can be generated and executed at compile time. Imagine a function declared like this

constexpr double myfunc(int x)

Now if you call it like this

constexpr double d1 = myfunc(1);
double d2 = myfunc(1);

You will have the value of d1 computed at compile time while d2 would be computed at runtime. constexpr is not related to template, though you can mix them together. For example here myfunc could be templatized. Would it execute compile time or run time, will depend on factors(like mentioned above).

constexpr, used with objects, would ensure they are compile-time initialized ( hence const by default). That's why in above case, 'context' for d1, forces myfunc to be executed compile time.

Upvotes: 8

Related Questions