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

前端 未结 5 1383
半阙折子戏
半阙折子戏 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:12

    I think you take 1 preprocessor and write your source code inside that.

    bool flag = false;
    #ifdef _MY_FRIEND_
        friend class sample
        flag = true;
    #endif
    
    if (flag)
    {
     ...
     ...
     ...
    }
    

    class Foo {
    #ifdef _MY_FRIEND_
        friend class Bar;
    #endif
    }
    

    };

    Here _MY_FRIEND_ is a preprocessor and if you add that preprocessor then at compile time your class Bar will be the friend class...you can use that preprocssor any where when you want to need class Bar as a friend class.other wise compile without the preprocessor then it wont allow u to add Bar as a friend class of Foo

    Please correct me if i understood the question wrong.

提交回复
热议问题