C++ 递归嵌套类型和名称注入
c++ recursively nested types and name injection
我试着在谷歌上搜索这个没有运气,所以我在这里尝试。
我有几个类,每个类定义一个成员struct foo
。此成员类型foo
本身可以从以前的类之一继承,因此foo
自身获取成员类型。
我想使用模板元编程访问嵌套的foo
类型(见下文),但是 c++ 名称注入带来了问题,因为上部foo
类型名称被注入到下部foo
类型中,而上层名称在我想访问下层类型时得到解决,例如使用 A::foo::foo
.
下面是一个示例:
#include <type_traits>
struct A;
struct B;
struct A {
struct foo;
};
struct B {
struct foo;
};
struct A::foo : B { };
struct B::foo : A { };
// handy c++11 shorthand
template<class T>
using foo = typename T::foo;
static_assert( std::is_same< foo< foo< A > >, foo< B > >::value,
"this should not fail (but it does)" );
static_assert( std::is_same< foo< foo< A > >, foo< A > >::value,
"this should fail (but it does not)" );
仅供参考,我正在实现函数导数,foo
是导数类型。上述情况发生,例如 sin/cos。
TLDR:我如何让foo<foo<A>>
foo<B>
,而不是foo<A>
?
谢谢!
这不是一个真正的自动解决方案,但解决了问题。你类型为基类提供 typedef,不存在/存在此typedef 通过 SFINAE 检测到,并且找到嵌套的 foo通过基本或通过正常查找。
您可能可以自动执行has_base
以检查已知列表如果您需要更多自动化,则以is_base_of
为基础。
#include <type_traits>
template <typename T>
struct has_base
{
typedef char yes[1];
typedef char no[2];
template <typename C>
static yes& test(typename C::base*);
template <typename>
static no& test(...);
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
struct A {
struct foo;
};
struct B {
struct foo;
};
struct A::foo : B { typedef B base; };
struct B::foo : A { typedef A base; };
template<typename T, bool from_base = has_base<T>::value >
struct foo_impl {
typedef typename T::base::foo type;
};
template<typename T>
struct foo_impl<T, false> {
typedef typename T::foo type;
};
template<typename T>
using foo = typename foo_impl<T>::type;
static_assert( std::is_same< foo< foo<A> >::, foo< B > >::value,
"this should not fail (but it does)" );
static_assert( std::is_same< foo< foo< A > >, foo< A > >::value,
"this should fail (but it does not)" );
int main()
{
return 0;
}
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 如何使用递归打印修改后的星号三角形图案
- 使用递归模板动态分配的多维数组
- 递归函数有效,但无法记忆
- C++ 递归嵌套类型和名称注入