C++ 递归嵌套类型和名称注入

c++ recursively nested types and name injection

本文关键字:注入 递归 嵌套类型 C++      更新时间:2023-10-16

我试着在谷歌上搜索这个没有运气,所以我在这里尝试。

我有几个类,每个类定义一个成员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;
}