How to use implicit template type deduction

  • A+

I am trying to write a template to calculate the power of a number during compile time(i am not a template meta-programming expert so any comment is appreciated). Below the code:

template<typename T, T X, int64_t P> struct Pow {     static constexpr T result = X * Pow<T,X, P - 1>::result; }; template<typename T, T X> struct Pow<T, X, 0> {     static constexpr T result = 1; }; template<typename T, T X> struct Pow<T, X, 1> {     static constexpr T result = X; }; 

which i need to call like:

Pow<decltype(4), 4, 2>::result 

Question:Is there anyway in writing a helper template so that the call skips the decltype. For example:

Pow<4, 2>::result 

I have read the following but so far i couldn't see an answer(it seems quite the opposite) this , this and this

If you downvote please explain why so i don't remain ignorant for eternity. Thank you very much for your time


Starting from C++17, you can use auto

template<auto X, int64_t P> struct Pow {     static constexpr decltype(X) result = X * Pow<X, P - 1>::result; };  template<auto X> struct Pow<X, 0> {     static constexpr decltype(X) result = 1; }; 

And you can also see that, given the 0 partial specialization, the 1 partial specialization is superfluous (also C++11/C++14).

Before C++17... the best I can imagine, to avoid to explicit the T type, pass through a macro definition (that usually is heavily discouraged but, in this case, I suppose can be reasonable).

Something as

#define PowMacro(X, P)  Pow<decltype(X), X, P>  


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: