用于检测非继承typedef的特性

Trait to detect non-inherited typedef

本文关键字:typedef 继承 检测 用于      更新时间:2023-10-16

如果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

在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 {};

实时演示