Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template argument type deduction

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?

like image 229
Dominic Dos Santos Avatar asked Feb 08 '17 22:02

Dominic Dos Santos


1 Answers

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

like image 107
Yakk - Adam Nevraumont Avatar answered Oct 10 '22 22:10

Yakk - Adam Nevraumont