Re: Why does this template code compile?
On 1/3/2014 7:25 PM, Peter wrote:
In "C++ Templates The Complete Guide" book by Vandevoorde
and Josuttis I found the following template definition
near the end of chapter 8.2 ("Template Arguments"):
template<template<typename T, T*> class Buf>
class Lexer
{
static char storage[5];
Buf<char, &Lexer<Buf>::storage> buf;
};
Buf is a template template argument whose template
arguments are: type parameter T and unnamed non-type
parameter - a pointer to T. In the definition of Lexer,
Buf is instantiated so that T = char and second argument
(of type T*) is &Lexer<Buf>::storage, but why is this
second substitution correct?
How does &Lexer<Buf>::storage resolve to char*?
I think it doesn't "resolve". Not until you actually instantiate the
template.
Here's my reasoning.
Lex<Buf>::storage is of type char[5],
&Lex<Buf>::storage is of type char(*)[5].
No. It's not. &(Lex<Buf>::storage) would be a pointer to an array.
But since the parentheses are missing (see 5.3.1), the expression is a
pointer-to-member.
If we had:
Buf<char, Lexer<Buf>::storage> buf;
instead of:
Buf<char, &Lexer<Buf>::storage> buf;
in the definition of Lexer template then
Lexer<Buf>::storage would decay to char*, but why
can the template be instantiated with
&Lexer<Buf>::storage as well? I tested both definitions
here:
http://www.compileonline.com/compile_cpp11_online.php
and they both compile.
Unless you try to instantiate the 'Lexer' template, the code only
undergoes syntax check and not the actual compilation (no conversions
are attempted).
However, if I try to instantiate Lexer with
&Lexer<Buf>::storage as second argument to Buf, I get
a compilation error as expected. Here's a complete example:
template<template<typename T, T*> class Buf>
class Lexer
{
static char storage[5];
Buf<char, &Lexer<Buf>::storage> buf;
};
template<typename T, T*>
class Foo
{
};
int main()
{
Lexer<Foo> lex;
return 0;
}
Now:
1) if I try to compile the above I get the following error:
main.cpp: In instantiation of 'class Lexer<Foo>':
main.cpp:15:15: required from here
main.cpp:5:37: error: could not convert template argument
'& Lexer<Foo>::storage' to 'char*'
2) if I change "&Lexer<Buf>::storage" to
"Lexer<Buf>::storage" the code compiles
3) if I comment out the instantiation of Lexer from main()
the code compiles with either &Lexer<Buf>::storage or
Lexer<Buf>::storage as second argument to Buf.
Which most likely means that the conversion is never attempted.
Can you explain what happens here and why Buf template can
be instantiated with either of the two arguments?
I can't explain how 'Buf' can be instantiated if it acutally can't be
instantiated (you get the error when you try to instantiate it).
V
--
I do not respond to top-posted replies, please don't ask