有没有办法检测 struct
是否有 typedef
不是继承的?
以下代码在 C
上失败
#include <iostream>
struct A { };
struct B : public A { typedef A Base; };
struct C : public B {};
template<typename T>
struct to_void
{
typedef void type;
};
template <typename T, typename dummy = void>
struct has_base_typedef : std::false_type {};
template <typename T>
struct has_base_typedef<T, typename to_void<typename T::Base>::type> : std::true_type {};
int main()
{
std::cout << has_base_typedef<A>::value;
std::cout << has_base_typedef<B>::value;
std::cout << has_base_typedef<C>::value;
}
C
的特征给出 true
因为 Base
是继承的(private
修饰符对 AFAIK 没有帮助)
我的目标是让代码片段打印010
Small example在ideone上玩。
最佳答案
基本上,您想阻止 Base
别名隐式传播到派生类,我认为这是不可能的。我能想到的实现接近你想要的东西的唯一方法如下:
struct C;
struct A {};
struct B : public A {
using Base = A;
using Derived = C;
};
struct C : public B { };
template<typename T>
struct to_void {
typedef void type;
};
template <typename T, typename dummy = void>
struct has_base_typedef : std::false_type {};
template <typename T>
struct has_base_typedef<T, std::enable_if_t<!std::is_same<typename T::Derived, T>::value,
typename to_void<typename T::Base>::type>> : std::true_type {};
关于c++ - 检测非继承 typedef 的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33898977/