如何确定类型是否是任何类型的模板化类型?

在下面的代码中:

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
}

居住


以上是如何确定类型是否是任何类型的模板化类型?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>