C++-递归结构-是可能的吗

C++ - Recursive structure - is it possible?

本文关键字:递归 结构 C++-      更新时间:2023-10-16

我正试图在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()返回的值是typefoo()的两倍。但正如我在评论中指出的那样,我的方法有几个问题,遗憾的是它不起作用。

这样的结构可以在C++中以某种方式声明吗,或者可能不可能?

有点像。这是在C++中实现类型递归的方法。

template< int tag >
struct X
{
    static constexpr int foo() { return 2 * X<tag-1>::foo(); }
};
template< >
struct X<1>
{
    static constexpr int foo() { return 1; }
};
#include <iostream>
using namespace std;
int main()
{
    static_assert(X<1>::foo() == 1, "Nope");
    static_assert(X<2>::foo() == 2, "Nope");
    static_assert(X<3>::foo() == 4, "Nope");
    cout << X<10>::foo() << endl;
}

是的,借用Let_Me_Be可以获得您要求的行为:

template< int tag >
struct X
 {
    static constexpr int foo() { return 2 * X<tag-1>::foo(); }
     typedef X<tag+1> recursive_type;
};

template< >
struct X<0>
{
    static constexpr int foo() { return 1; }
    typedef X<1> recursive_type;
};
typedef X<0> 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的深度递归使用写成X<n>。。。