Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A template that accepts only pointer type arguments

After seeing that a template can be partially specialized for reference or pointer types, I was wondering whether I can write a template that accepts only a pointer type to start with. This is my attempt:

template <typename T*>
struct MyTemplate{};

int main() {
    MyTemplate<int *> c;
    (void)c;
    return 0;
}

This does not compile. How should it be modified? (i.e. if what I am trying to accomplish is at all possible)

like image 797
AlwaysLearning Avatar asked Aug 02 '15 07:08

AlwaysLearning


People also ask

Can template type be a pointer?

A template has only one type, but a specialization is needed for pointer, reference, pointer to member, or function pointer types. The specialization itself is still a template on the type pointed to or referenced.

What is a template argument?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

What is a non-type template parameter?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.

What is non-type template arguments in C++?

A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.


1 Answers

You may use partial specialization:

template <typename T> struct MyTemplate; // Declaration

template <typename T> struct MyTemplate<T*> // Specialization
{
};

or use 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>;
};
like image 144
Jarod42 Avatar answered Nov 08 '22 16:11

Jarod42