Consider the following code:
#include <iostream>
struct foo {
friend void bar(foo) {}
void foobar() {
std::cout << &bar << '\n'; // error
}
};
int main() {
bar(foo{}); // ok, visible through ADL
foo{}.foobar();
}
gcc gives me this error:
main.cpp: In member function 'void foo::foobar()': main.cpp:7:23: error: 'bar' was not declared in this scope std::cout << &bar << '\n'; // error ^~~
That's because bar
is a friend function defined in the class itself, making it invisible in the global namespace. The only way to access it is through ADL, but I have not found a way to use ADL to get the address of bar
.
So my question is, how can I take the address of bar
? Is there any other way than to define bar
outside of foo
?
You could declare the friend function in the enclosing namespace scope in a different translation unit:
In foo.hpp:
#include <iostream>
struct foo;
void (*get_bar_address())(foo);
struct foo {
friend void bar(foo) {}
void foobar() {
std::cout << get_bar_address() << '\n'; // no error
}
};
In foo.cpp
#include "foo.hpp"
void bar(foo);
void (*get_bar_address())(foo){
return bar;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With