首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查类是否继承自模板的任何模板实例化。

检查类是否继承自模板的任何模板实例化。
EN

Stack Overflow用户
提问于 2014-03-23 14:49:24
回答 1查看 2.6K关注 0票数 7

我编写了一个小型实用程序,用于测试类型是否继承了特定模板类的模板实例化,或者直接继承了继承模板的类,或者继承了继承模板的类。这是通过使用模板函数接受所提供模板的任何模板实例化和默认情况下的回退重载的SFINAE检查来实现的。

代码语言:javascript
复制
#include <iostream>
#include <type_traits>

template<template<class> class T, class U>
struct isDerivedFrom
{
    static constexpr bool value = decltype(isDerivedFrom::test(U()))::value;
private:
    template<class V>
    static std::true_type test(T<V>);
    static std::false_type test(...);
};

template<class T>
struct Base {};
struct Base_D1 : Base<int> {};
struct Base_D2 : Base<Base_D2> {};
struct Base_D1_D1 : Base_D1 {};
struct NotDerived {};

int main()
{
    std::cout << std::boolalpha
        << "is Base_D1 derived from or a template instantiation of Base: "
        << isDerivedFrom<Base, Base_D1>::value << "\n"
        << "is Base_D2 derived from or a template instantiation of Base: "
        << isDerivedFrom<Base, Base_D2>::value << "\n"
        << "is Base_D1_D1 derived from or a template instantiation of Base: "
        << isDerivedFrom<Base, Base_D1_D1>::value << "\n"
        << "is Base<double> derived from or a template instantiation of Base: "
        << isDerivedFrom<Base, Base<double>>::value << "\n"
        << "is NotDerived derived from or a template instantiation of Base: "
        << isDerivedFrom<Base, NotDerived>::value << "\n";
    return 0;
}

输出:

代码语言:javascript
复制
is Base_D1 derived from or a template instantiation of Base: true
is Base_D2 derived from or a template instantiation of Base: true
is Base_D1_D1 derived from or a template instantiation of Base: true
is Base<double> derived from or a template instantiation of Base: true
is NotDerived derived from or a template instantiation of Base: false

我的问题是,如果要测试的类型(isDerivedFrom的模板参数T)具有或继承非公共构造函数或通过非公共继承继承模板,则会导致编译错误,因为如果T::T()不是公共的,则T::T()失败:

代码语言:javascript
复制
struct Base {protected: Base(){}};
struct Derived : private Base<int> {};

有什么办法让这件事适用于所有案件吗?代码中是否有未提及的问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-23 15:07:14

您可以使用:https://ideone.com/wR2dLX

代码语言:javascript
复制
template<template<class> class T, class U>
struct isDerivedFrom
{
private:
    template<class V>
    static decltype(static_cast<const T<V>&>(std::declval<U>()), std::true_type{})
    test(const T<V>&);

    static std::false_type test(...);
public:
    static constexpr bool value = decltype(isDerivedFrom::test(std::declval<U>()))::value;
};

由于私有继承不可见,在最后一种情况下,该特性返回false (对于struct Derived : private Base<int> {};)。

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22592419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档