I was reading this and was trying to understand what N3601 was about. It said this idiom comes up a lot in a web search, but I couldn't find anything. What is the
template<typename T, T t>
idiom, what does it solve, how is it used, what is are Implicit template parameters, and what does the proposal aim to fix?
The problem that is being solved is deducing types from template non-type parameters.
Given:
template<typename T> void foo(T); template<typename T, T> void bar();
it is possible to deduce T
for foo
(for example, foo(10)
will result in T
being deduced to be int
), but it is not possible to deduce T
for bar
(bar<10>()
will simply not compile, you have to write it as bar<int,10>()
).
N3601 proposes fixing this by introducing the syntax:
template<using typename T, T> void bar();
which will allow bar<10>()
to compile and cause the type T
to be deduced.
The paper introduction is misleading: the idiom is actually
template <typename T, T t>
It denotes a template which depends on a type T
and a value t
of that type. The notation is a bit heavy since in most situations the type could be deduced from the value itself.
E.g.
// the current definition notation template <typename T, T t> void f() { t.f(); }; //// the proposed definition notation //// the parameter t depends on an implicit typename parameter T // template <using typename T, T t> void f() { t.f(); }; struct foo { void f(){ // some computation } }; foo bar; int main(){ // the current instantiation notation f<foo,bar>(); //// the proposed instantiation notation //// we know that bar is of type foo, so we don't need to specify it // f<bar>(); }
The proposal is about introducing a bit of "syntactic sugar" to make the notation easier to write.
Also, the example given above is trivial in its description (and possibly wrong, since template parameters need to be constexpr
), but the paper describes several situations where the current notation can become quite hairy, reducing readability and overall ease of programming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With