如何确定一个类型是否是某个特定类型的模板化类型

How to find out if a type is a templated type of some specific type?

本文关键字:类型 是否是 一个 何确定      更新时间:2024-05-23

在下面的代码中:

template <typename T>
struct templatedStruct
{
};
template <typename T>
void func(T arg)
{
// How to find out if T is type templatedStruct of any type, ie., templatedStruct<int> or
// templatedStruct<char> etc?
}
int main()
{
templatedStruct<int> obj;
func(obj);
}

从其他东西继承templatedStruct的唯一方法是什么?

struct Base {};
template <typename T>
struct templatedStruct : Base
{
};
template <typename T>
void func(T arg)
{
std::is_base_of_v< Base, T>;
std::derived_from<T, Base>; // From C++ 20
}

您可以为其定义类型特征。

template <typename T>
struct is_templatedStruct : std::false_type {};
template <typename T>
struct is_templatedStruct<templatedStruct<T>> : std::true_type {};

然后

template <typename T>
void func(T arg)
{
// is_templatedStruct<T>::value would be true if T is an instantiation of templatedStruct
// otherwise false
}

实时

您可以编写一个重载集,该集返回处理不同情况的结果,并相应地返回一个布尔值:

template <typename T>
constexpr bool check(T const &) { return false; }
template <typename T>
constexpr bool check(templatedStruct<T> const &) { return true; }

然后像这样使用:

template <typename T>
void func(T arg)
{
if(check(arg)) // this could be 'if constexpr' if you want only
// one branch to be compiled
// ...
}