我想實現C++遞歸結構,東西應該看起來有點像這樣:C++ - 遞歸結構 - 有可能嗎?
typedef struct {
static constexpr int foo() {
return 1;
}
typedef struct {
// not valid - I meant foo() from "type" not from "recursive_type"
static constexpr int foo() {
return 2 * foo();
}
// ? (there should be another recursive type here)
} recursive_type;
} type;
而且應該像這樣工作:
static_assert(type::foo() == 1, "Nope");
static_assert(type::recursive_type::foo() == 2, "Nope");
static_assert(type::recursive_type::recursive_type::foo() == 4, "Nope");
基本上 - 我想recursive_type
遏制結構看起來完全像type
,但其foo()
返回值爲type
的foo()
的值的兩倍。但正如我在評論中指出的那樣,我的方法存在一些問題,可惜它不起作用。
這樣的結構可以用C++聲明嗎,或者它不可能?
你會更好地使用指針,也許智能的指針。避免用相同的名稱命名兩個'struct'(在同一個翻譯單元中)。 –
是的,我知道我可以使用指針來做到這一點,但我需要一個對象,其語義看起來像我所描述的。 (所以'recursive_type'應該稍微修改它所調用的對象的修改版本) – qiubit
您是否考慮切換到Ocaml。它有遞歸函子... –