【问题标题】:Is it possible to check if a object is equal to a template class without specifying the template type?是否可以在不指定模板类型的情况下检查对象是否等于模板类?
【发布时间】:2020-06-07 10:21:46
【问题描述】:

假设我有课:

template<typename T>
class ChartData {
public:
...

现在我想检查对象 value 是否是 ChartData 对象:

if (value.type() == typeid(ChartData*))

但是这会导致错误

类模板的参数列表丢失

所以编译器希望我将类型放在 ChartData* 但是在这种情况下我对类型不感兴趣 - 我只想知道该对象是否是 ChartData 对象的实例。

这可能吗?如果有,怎么做?

【问题讨论】:

  • 不是在运行时,不是。但是youtr 模板的基类呢?
  • 没有ChartData 的实例没有,因为ChartData 不是类型——它是用于创建类型的模板。模板的实例化是类型,但它们不相关,就好像你是手写出来的一样。

标签: c++ class templates types typeid


【解决方案1】:

类似的东西:

template <typename T>
struct IsChartData : public std::false_type {};

template <typename T>
struct IsChartData<ChartData<T>> : public std::true_type {};

if (IsChartData<decltype(value)>()) {...}

【讨论】:

    【解决方案2】:

    你可以使用模板元编程

    #include <type_traits>
    
    template<class, template<class...> class>
    struct is_specialization : std::false_type {};
    
    template<template<class...> class temp, class... tempargs>
    struct is_specialization<temp<tempargs...>, temp> : std::true_type {};
    
    template<class>
    struct dummy {};
    int main () {
        dummy<int> d;
        static_assert(is_specialization<decltype (d), dummy>::value);
    }
    

    这适用于只有类型模板参数的所有模板。如果你有混合类型和非类型,这在一般情况下实际上是不可行的,但你当然可以为一个特定的模板和合适的参数编写上面的内容。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多