仅接受指针类型参数的模板

Alw*_*ing 9 c++ templates partial-specialization c++11

在看到模板可以部分专用于引用或指针类型之后,我想知道我是否可以编写一个只接受指针类型的模板.这是我的尝试:

template <typename T*>
struct MyTemplate{};

int main() {
    MyTemplate<int *> c;
    (void)c;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这不编译.应该如何修改?(即如果我想要完成的任务是可能的话)

Jar*_*d42 14

您可以使用部分专业化:

template <typename T> struct MyTemplate; // Declaration

template <typename T> struct MyTemplate<T*> // Specialization
{
};
Run Code Online (Sandbox Code Playgroud)

或使用 static_assert

template <typename T> struct MyTemplate
{
    static_assert(std::is_pointer<T>::value, "Expected a pointer");

    // T = value_type*
    using value_type = std::remove_pointer_t<T>;
};
Run Code Online (Sandbox Code Playgroud)