Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My template function with the universal reference does not work

Tags:

c++

c++14

I want to make a template function that is flexible and can take both rvalue and lvalue. This is how I wrote it:

template<typename T>
decltype(auto) normalize_pose(T&& pose)
{
    if (pose > 2 * M_PI) return std::forward<T>(pose - 2* M_PI);
} 

So I double checked the function and it seems correct to me. Then I have decided to test it and wrote:

int a = 2;
auto test = factorgraph::normalize_pose(a);

I get this error:

 error: use of ‘decltype(auto) factorgraph::normalize_pose(T&&) [with T = int&]’ before deduction of ‘auto’

If I try to add <int>, I get an error that no such function exist.

like image 758
aikhs Avatar asked Apr 14 '26 04:04

aikhs


1 Answers

It should be

if (pose > 2 * M_PI) return std::forward<T>(pose) - 2* M_PI;

Apply std::forward to variable only.

And you also need to return value for the else branch (of the same type to satisfy decltype(auto)).

But in your case, a simple:

template<typename T>
auto normalize_pose(const T& pose)
{
    return (pose > 2 * M_PI) ? pose - 2 * M_PI : pose;
}

handles all cases.

like image 172
Jarod42 Avatar answered Apr 16 '26 02:04

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!