问题描述
仅当某些(编译时)条件为true时,我才想声明一个朋友类.例如:
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;
}
};
我在互联网上找不到任何解决方案.我仔细研究了在编译时动态生成结构的所有答案.他们中的许多人都使用C ++ 11 std::conditional
,但是我想知道是否有可能在不使用预处理器的情况下在C ++ 03 中做到这一点.
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.
此解决方案 https://stackoverflow.com/a/11376710/252576 将不起作用,因为friend
ship不被继承(具有继承关系的朋友类).
This solution https://stackoverflow.com/a/11376710/252576 will not work because friend
ship is not inherited ( friend class with inheritance ).
编辑,只是为了使它更容易显示,如下面的注释中所述:此要求是不寻常的.这是我正在从事的硬件仿真新研究项目的一部分.测试平台是用C ++编写的,我想以波形形式显示变量.我研究了各种其他选择,并出于实际考虑,发现需要使用friend class
.朋友将捕获这些值并生成波形,但是我更希望仅在需要波形时才与朋友互动,而不是一直与朋友互动.
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.
推荐答案
使用friend std::conditional<C, friendclass, void>::type;
,其中C
是您的条件.非类类型的朋友将被忽略.
Use friend std::conditional<C, friendclass, void>::type;
where C
is your condition. A nonclass type friend will be ignored.
条件模板很容易在C ++ 03中实现.但是,由于C ++ 03不支持typedef朋友,因此您需要在其中使用以下语法
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.
这篇关于可以在C ++ 03中有条件地声明friend类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!