4

Suppose we want to write a function which is supposed to get a value as a template parameter (for, say, efficiency reasons), but we don't know in advance the type of the parameter we're expecting. It is possible to implement it as

template<typename T, T val> func() { cout << val; } 

However, it is not fun to call such a function

func<int, 5>() 

is it possible to rewrite func s.t. we can call it in the following way?

func<5>() 
5
  • 1
    Might work with the auto type. Commented Sep 5, 2016 at 17:51
  • 2
    open-std.org/JTC1/SC22/WG21/docs/papers/2016/p0127r2.html Commented Sep 5, 2016 at 17:51
  • 2
    Why not template<typename T> constexpr void func(T val) { } and call it as f(5)? Commented Sep 5, 2016 at 17:55
  • You do know that template types can only be simple types, like int and bool. You can't put a double, for example, instead of that int, right? So I'm wondering whether it's ever useful to do this. Commented Sep 5, 2016 at 19:21
  • How about template<typename T, T val> func(std::integral_constant<T, val>) { cout << val; } Commented Sep 5, 2016 at 19:54

1 Answer 1

5

A solution that mostly depends on your actual function is to define it as it follows:

template<typename T> constexpr void func(T val) { } 

Then invoke it as f(5) and have the template parameter deduced from the parameter of the function itself.

Otherwise, in C++14, you cannot avoid using the pattern template<typename T, T value>.
It is the same pattern used by the Standard Template Library, see as an example the definition of std::integral_constant.

A possible solution that mitigates (maybe) the boilerplate is based on the use of a struct, as an example:

template<typename T> struct S { template<T value> static void func() {} }; 

You can the do something like this:

using IntS = S<int>; // .... IntS::func<5>(); 

With the upcoming revision C++17, you will manage to do it as it follows:

template<auto value> void func() {} 

This can be invoked as f<5>(), that is what you are looking for..

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.