Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the address of an inline defined friend function

Tags:

c++

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?

like image 817
Rakete1111 Avatar asked May 25 '17 17:05

Rakete1111


1 Answers

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;
}
like image 172
Oliv Avatar answered Sep 21 '22 23:09

Oliv