Re: Why internal linkage variables can't be used to instantialize an template?
On Mar 26, 2:51 am, "h.yuz...@gmail.com" <h.yuz...@gmail.com> wrote:
External linkage variable can be used as template's non-type
parameters. But internal not even if the value of it can be evaluated
at compiling time. Why? Thank you all. The code snipet like follow:
int i1 = 1;
static int i2 = 2;
template<const int& i> void f() {}
int main()
{
f<i1>();
f<i2>(); /*Error: an expression involving objects with internal
linkage cannot be used as a non-type argument*/
}
Since templates themselves have external linkage, their type and non-
type arguments have to have external linkage as well - otherwise there
would be no assurance that each instantiated tenplate had its own
unique name. For example, if f<i2> were a legal template instantiation
then there would be nothing to prevent another source file from
likewise instantiating f - but with its own, local i2. So the program
would wind up with two different f<i2> types and no way to tell them
apart given that their names would be the same..
Fortunately, the Standard anticipated that a C++ program may wish to
instantiate a template with a "local" type (or non-type) argument and
provided a way to do so (or at least to achieve the same effect):
int i1 = 1;
namespace
{
int i2 = 2;
}
template<const int& i> void f() {}
int main()
{
f<i1>();
f<i2>(); // OK
}
Variables declared within an anonymous namespace are "local" (that is,
inaccessible from other translation units) yet nontheless have
external linkage - making them suitable template arguments.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]