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

时间:2012-10-17 15:20:42

标签: c++ c++11 nested code-injection typename

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

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

谢谢!

1 个答案:

答案 0 :(得分:1)

这不是一个真正的自动解决方案,但解决了这个问题。您的 types为基类提供了一个typedef,缺少/存在 通过SFINAE检测到typedef,并找到嵌套的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;
}