如何创建指针类的静态模板函数

how to create a static template function to a pointer class?

本文关键字:静态 函数 指针 何创建 创建      更新时间:2023-10-16

我的模板类A包含一个调用模板类静态函数的函数:

template <typename T>
void A<T>::fun() {
    T obj = T::create();
    ....
}

如果我想让这段代码在T = B*时工作,我应该如何修改这一点?我知道我不能做(*T)::create(),但从概念上讲,这就是我想要的。

您可以使用std::remove_pointer类型性状:

#include <type_traits>
template <typename T>
void A<T>::fun() {
    T obj = std::remove_pointer<T>::type::create();
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    // ...
}

其中std::remove_pointer<U*>::typestd::remove_pointer<U>::type均为U