How can I enable ADL in a constructor initialization list? For example, let's say that I have a bignum
that has a namespace-level abs
function. Now I want to write a class Foo
that initializes its members with the absolute values of the instances passed to the constructor; it should the use namespace-level abs
if it exists and std::abs
otherwise:
template<typename T>
struct Foo
{
T _data;
Foo(T data):
_data(abs(data)) // I want find abs with ADL here
{}
};
Using declarations are forbidden at class scope anyway and I don't want to "pollute" the namespace. How can I enable the ADL so that it works in the constructor initialization list?
You can solve this directly from within the initialiser list, by using a lambda expression: it allows you to write the required helper function inline, and that helper function can contain using std::abs;
.
template<typename T>
struct Foo
{
T _data;
Foo(T data):
_data([&](){ using std::abs; return abs(data); }())
{}
};