I have such a template in C++
template<typename T, T* P> struct Ptr {};
so I can use it as such:
const int i = 0;
Ptr<int, &i> ptr;
or
Ptr<decltype(i), &i> ptr;
But I don't want to specify the type int
or identity i
twice, I want to use just
Ptr<&i> ptr;
and let the compiler figure out the int
type part by itself.
How can I declare my template to do that ?
I've read this question but the answer is using macros, that's not nice: template of template c++?
can I do this by just template without macros ? I'm using Visual C++ 2013.
UPDATE
c++17 introduced "P0127R2 Declaring non-type template parameters with auto", allowing to declare a non-type template parameter(s) with
auto
as a placeholder for the actual type:That is,
P
is a non-type template parameter. Its type can be inferred withdecltype(P)
.auto
in a template parameter list is subject to well-known deduction and partial ordering rules. In your case, the type can be constrained to accept pointers only:Note that the syntax utilizing
auto
is sufficient even for more detailed inspection, e.g.:It's also possible to use the inferred type as a contraint for other template parameters:
Old answer
Since you are asking about a pure class template-based solution without the help of macro definitions then the answer is simple: as for now (Dec 2014, c++14) it is not possible.
This issue has been already identified by the WG21 C++ Standard Committee as a need and there are several proposals to let templates automatically infer the type of non-type template arguments.
The closest is N3601 Implicit template parameters:
A similar proposal is the one included in N3405 Template Tidbits:
The current status of both proposals can be tracked under EWG issue 9.
There are some other discussions proposing alternative syntax with
auto
: