ohad ohad - 3 months ago 14
C++ Question

C++ template argument of unknown type

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>()

Answer

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..