I want to declare a friend class only if some (compile-time) condition is true. For example:
// pseudo-C++
class Foo {
if(some_compile_time_condition) {
friend class Bar;
}
};
I did not find any solution on the internet. I went through all the answers to the question Generating Structures dynamically at compile time. Many of them use the C++11 std::conditional, but I would like to know if it is possible to do this in C++03 without using the preprocessor.
This solution https://stackoverflow.com/a/11376710/252576 will not work because friendship is not inherited ( friend class with inheritance ).
Edit Just to make this more easily visible, as mentioned below in the comment: This requirement is unusual. This is part of a new research project in hardware simulation, that I am working on. The testbench is written in C++, and I want to display the variables in a waveform. I have researched various other options, and figured out that I need to use a friend class, due to practical considerations. The friend will capture the values and generate the waveform, but I would prefer to have the friend only when the waveform is required, and not all the time.
We can declare both a member function and a free function as a friend in the class body. For a free function, it is very straightforward and a forward declaration is not required. We can simply declare the friend as follows: The void Print(const Test& test) function has access to the private members of the Test class.
Friend function can be declared in any section of the class i.e. public or private or protected.
The friend function can be a member of another class or a function that is outside the scope of the class. A friend function can be declared in the private or public part of a class without changing its meaning. Friend functions are not called using objects of the class because they are not within the class's scope.
Use friend std::conditional<C, friendclass, void>::type; where C is your condition. A nonclass type friend will be ignored.
The conditional template is easily implemented in C++03. However since C++03 does not support typedef friends you need to use the following syntax there
namespace detail { class friendclass {}; }
class Foo {
friend class std::conditional<C,
friendclass, detail::friendclass>::type::friendclass;
};
Note that the detail dummy class name needs to match the name of the potential friend in this workaround.
[class.friend]/3 tells this :
A friend declaration that does not declare a function shall have one of the following forms:
friend elaborated-type-specifier ;friend simple-type-specifier ;friend typename-specifier ;
therefore it is not possible to conditionally declare friends of a class, without a macro.
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