Given a templated function declared like this:
template<class T>
int Function(T object);
A user can invoke this function by specifying the templated type, like this:
int result = Function<float>(100.f); // Valid
But the type specification is optional, as the compiler can deduce the type of T from the supplied argument's type; like this:
int result = Function(100.f); // Also valid, the compiler deduced the type "float" from the literal's type
Let's say I get a little more complicated, and I want a templated value parameter like this:
template<class T, T* object>
int Function();
I can call my function in this way:
static float val = 100.f;
// ...
int result = Function<float, &val>();
My question is: is there any way I coerce the compiler to deduce the type T based on the type of the argument &val?
What I need is a way to make the following code valid:
static float val = 100.f;
// ...
int result = Function<&val>();
Can it be done?
In C++17, you can have auto
non-type template parameters. This will let you solve your problem.
Something like:
template<auto object, class T=std::decay_t<decltype(*object)>>
int Function();
(assuming you want the type T
within the body of Function
)
In C++14, the C++17 feature is missing. It was added exactly because it was missing. Workarounds involve macros like #define UGLY_HACK(...) decltype(__VA_ARGS__), __VA_ARGS__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With