Can friend class be declared conditionally in C++03?

前端 未结 5 1425
半阙折子戏
半阙折子戏 2021-01-19 02:54

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) {
         


        
5条回答
  •  独厮守ぢ
    2021-01-19 03:26

    Note: Johannes has pretty much nailed it. In '03 you cannot befriend a typedef - but if you know you have a class, then you can refer to it's injected class name.

    Johannes' answer also has the benefit of using standard library functionality which too is always a good thing.

    #define some_compile_time_condition 0
    
    class Foo;
    
    template  class  TestCondition {
    private:
      friend class Foo;
      struct Type {
        struct Bar;
      };
    };
    
    template <> class TestCondition<1> {
    public:
      typedef Bar Type;
    };
    
    struct Bar
    {
    public:
      void foo (Foo &);
    };
    
    class Foo {
    private:
      friend struct TestCondition< some_compile_time_condition >::Type::Bar;
      int m_i;
    };
    
    void Bar::foo (Foo & foo)
    {
      foo.m_i = 0;
    }
    

    It's still different to the requirement in that Foo always has a friend, but the befriended class changes based on the value of the option.

    An interesting side question is whether it is an ODR violation to have versions of Foo both with and without some_compile_time_condition set to 1.

提交回复
热议问题