C++-递归结构-是可能的吗
C++ - Recursive structure - is it possible?
我正试图在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++中以某种方式声明吗,或者可能不可能?
有点像。这是在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>
。。。
相关文章:
- 二叉树结构平衡,使用递归时EXC_BAD_ACCESS
- 如何在C++中表示JSON文档的递归对象结构?
- C++ 递归返回 nullptr 中的结构 ?.
- 递归如何使用堆栈数据结构
- 如何制作递归编译时间变异结构模板
- 没有指针的递归结构?(霍夫曼)
- 使用boost::序列化递归图结构时,如何防止堆栈溢出
- 递归结构的向量有内存问题
- C++,一个通用递归模板函数,用于遍历树状结构
- 如果结构作为递归函数中的参数传递,如何初始化结构的成员变量
- 节省增强精神递归匹配结果为C 结构
- 用载体建立在苍蝇递归结构上
- 双递归结构
- 如何计算递归结构
- 使用结构和递归查找整数数组中的最大数字
- 正在分析boost::spirit上的递归结构
- C++-递归结构-是可能的吗
- 如何使用向量通过指针引用递归结构
- 你能解释一下指针和递归结构体吗?
- c++中的递归结构