我试图在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;
Run Code Online (Sandbox Code Playgroud)
这应该是这样的:
static_assert(type::foo() == 1, "Nope");
static_assert(type::recursive_type::foo() == 2, "Nope");
static_assert(type::recursive_type::recursive_type::foo() == 4, "Nope");
Run Code Online (Sandbox Code Playgroud)
基本上 - 我想recursive_type包含看起来完全相同的结构type,但它的foo()返回值是type's的两倍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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
119 次 |
| 最近记录: |