w00d
w00d

Reputation: 5596

C++ determine the type of auto and pass to function template

I have a function :

template<typename T> f(T x) { do something with x; }

I want to pass this auto pointer into the function

auto x = ...
f<???>(x)

Is there anyway for me to do so ?

Upvotes: 1

Views: 80

Answers (2)

AliciaBytes
AliciaBytes

Reputation: 7429

Just call it like

auto x = ...
f(x)

templated functions automatically deduce the type depending on the arguments you pass it. In fact that's the preferred way to call a templated function.

If you really want to explicitly give it the type (I don't recommend doing that) you can use decltype for it:

auto x = ...
f<decltype(x)>(x)

Here a minimal proof: http://coliru.stacked-crooked.com/a/d01070d90c0b9803

Upvotes: 5

Bryan Chen
Bryan Chen

Reputation: 46578

compiler should be smart enough to figure out the type, so

auto x = ...
f(x);

or you can use decltype

auto x = ...
f<decltype(x)>(x);

Upvotes: 3

Related Questions