0

In C++ I can do something like this:

template <typename T, T* Ptr>
class MyClass {};

I have two questions:

  1. Where can I get a pointer other than nullptr in compile time?

  2. How can I use this language feature? Of course, it would be interesting for practical cases, but it seems that this is a rather specific possibility, so an artificial example will also be suitable.

1
  • 2
    You can get a pointer to anything with static storage duration and linkage at compile time. Commented Jan 12, 2021 at 8:46

1 Answer 1

3

You can get a pointer to anything with static storage duration and linkage at compile time:

static const int values[] = {4, 8, 15, 16, 23, 42};
MyClass <const int, values> myClass;

static char magic = '*';
MyClass <char, &magic> myClass2;

Demo

Sign up to request clarification or add additional context in comments.

5 Comments

When it can be useful?
Whereas you need constexpr pointer in template, might be useful to add name to template class. I already used it to serialize classes into Json.
on option where it can be useful it in the embedded system where you have static memory maps for a different section - and it const.
@Jarod42, what means "to add name to template class"? You can also use empty struct for that. Or maybe this is one from all solutions?
It is one available tool. It (might) have alternative. Runtime pointer might also be enough. Can also be there in generic programming, so no special cases for pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.