gpt4 book ai didi

c++ - 检查类是否继承自模板的任何模板实例化

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:48 25 4
gpt4 key购买 nike

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

#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;
}

输出:

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)具有或继承非公共(public)构造函数或通过非公共(public)继承继承模板,则会导致编译错误因为如果 T::T() 不是公开的,decltype(T()) 会失败:

struct Base {protected: Base(){}};
struct Derived : private Base<int> {};

有什么方法可以使它适用于所有情况吗?代码是否有任何未提及的问题?

最佳答案

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

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

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

关于c++ - 检查类是否继承自模板的任何模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22592419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com