When I implement a class I start with public interface and then continue with private details, which I think creates a good order for those that read the code:
class Something
{
public:
// interface
private:
// implementation details
};
This poses problems related to type deduction:
class Something
{
public:
auto compute()
{
auto lambda = get_lambda(); // use of 'auto Something::get_lambda()' before deduction of 'auto'
return lambda();
}
private:
auto get_lambda()
{
return []{ return 5; };
}
};
To fix this, I can rearrange the sections, so that definition of get_lambda
is before definition of compute
. I would like to avoid this. An alternative would be to provide the return type of get_lambda
, but the straightforward way fails:
class Something
{
public:
auto compute()
{
auto lambda = get_lambda();
return lambda();
}
private:
auto get_lambda() -> decltype([]() { return 5; })
{
return []() { return 5; }; // could not convert '<lambda closure object>Something::get_lambda()::<lambda()>()' from 'Something::get_lambda()::<lambda()>' to 'Something::<lambda()>'
}
};
The examples above are just simplification to illustrate the problem. My original code is a bit more complex (function that plays the role of get_lambda
returns a composition of several views).
Is there some better way to overcome the problem?
You can implement the methods outside the class like this.
class Something
{
public:
auto compute();
private:
auto get_lambda();
};
inline auto Something::get_lambda()
{
return []{ return 5; };
}
inline auto Something::compute()
{
auto lambda = get_lambda();
return lambda();
}
Don't forget the inline keyword.