max*_*max 11 c++ nested code-injection typename c++11
我试着用谷歌搜索没有运气,所以我在这里尝试.
我有几个类,每个类都定义一个成员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)" );
Run Code Online (Sandbox Code Playgroud)
仅供参考,我正在实现函数导数,foo是衍生类型.上述情况发生在例如sin/cos.
TLDR:我怎么会foo<foo<A>>成为foo<B>,不是foo<A>吗?
谢谢 !
这并不是真正的自动解决方案,而是解决了问题。您的类型为基类提供了一个 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
354 次 |
| 最近记录: |