是否可以在不指定模板类型的情况下检查对象是否等于模板class?

Is it possible to check if a object is equal to a template class without specifying the template type?

假设我有 class:

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

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

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

但是这会导致错误

argument list for class template is missing

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

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

大致如下:

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

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

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

您可以使用模板元编程

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

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