Jump to content

  • Log In with Google      Sign In   
  • Create Account

Template non type parameters question


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 noatom   Members   -  Reputation: 782

Like
0Likes
Like

Posted 05 July 2014 - 06:31 PM

template <char const* name> 
class MyClass { 
  … 
}; 

So, apparently you cannot use literals with templates. The reason given is:

 

 

One of the problems with string literals is that two identical literals can be stored at two distinct addresses.

 

But what could happen in a worse case scenario? If it was allowed, then, could it happen that 2 exact same instances of a template would be created(because a new template instance is created for every combination of template parameters used in code), so, would that somehow pose a problem?



Sponsor:

#2 Servant of the Lord   Crossbones+   -  Reputation: 19579

Like
0Likes
Like

Posted 05 July 2014 - 07:32 PM

Remember that template arguments are used to generate entirely different functions. MyFunc<0>() and MyFunc<1>() are two separate functions, not values passed into a single function (the equivalent of MyFunc_0(), and MyFunc_1()).
 
Are you templating on the value of "Hello world", or the value of the address in the pointer? I think it's the latter, but I'm not sure. I mean, template<int *ptr>() - does this template on the address (i.e. the value of the pointer itself) or the value pointed to? I think it's the address...
 
With a string literal, each place you call the templated function could, potentially, be referring to a different function. If you try to intentionally take the address of a function to use it as a function pointer, you won't know which of two (or more!) addresses you've got to virtually-identical functions.
 
 
You're templating not on the value of the string literal itself, but on the value of the pointer (the address of the string literal). Further, the value needs to be valid at compile time.
 
Possible solution: Call the function with a compile-time hash of the string literal instead?

MyFunc<size_t myStrHash>(int) { ... }

MyFunc<CompileTimeHash("Hello!")>(27); //Calls MyFunc_4356721_int
MyFunc<CompileTimeHash("Hello!")>(53); //Calls MyFunc_4356721_int

I'm not sure if that'd actually work though - I don't know if templated arguments can take constexpr values.
 
[Edit:] Reading the standard (N3376, from early 2012, so semi-outdated), it looks like they can take constexpr function results.
 
It also gives an example where you can use a const char*, but only if (I think?) it has a known compile-time address:

 

14.3.2 Template non-type arguments [temp.arg.nontype]
A template-argument for a non-type, non-template template-parameter shall be one of:
for a non-type template-parameter of integral or enumeration type, a converted constant expression (5.19) of the type of the template-parameter ; or
the name of a non-type template-parameter ; or
a constant expression (5.19) that designates the address of an object with static storage duration and
external or internal linkage or a function with external or internal linkage, including function templates
and function template-id s but excluding non-static class members, expressed (ignoring parentheses) as
& id-expression , except that the & may be omitted if the name refers to a function or array and shall
be omitted if the corresponding template-parameter is a reference; or
a constant expression that evaluates to a null pointer value (4.10); or
a constant expression that evaluates to a null member pointer value (4.11); or
a pointer to member expressed as described in 5.3.1.
 
[ Note: A string literal (2.14.5) does not satisfy the requirements of any of these categories and thus is not
an acceptable template-argument . [ Example:
template<class T, const char* p> class X {
    /∗ ... ∗/
};

X<int, "Studebaker"> x1; // error: string literal as template-argument

const char p[] = "Vivisectionist";
X<int,p> x2; // OK
—end example ] —end note ]

 

(Copy+pasted - it's their wording entirely, their code snippet, their bullets, etc... I only formatted (spacing + italicizing/bolding and code box) it to make it not a wall of text)

 

It's rather difficult for me to understand all the lingo though. tongue.png I'm still new to trying to read these things.

 

I also came across this link, where some blogger talks a little about pointers in template arguments as he plays around with them.


Edited by Servant of the Lord, 05 July 2014 - 07:50 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#3 SeanMiddleditch   Members   -  Reputation: 5876

Like
0Likes
Like

Posted 05 July 2014 - 08:44 PM

The reason you can't use string literals as template parameters is much simpler: mangling of symbol names for linking.

Each template function needs to be mangled to a different unique name. Since foo<"bar"> in two different translation units would still need to be linked to the same definition, it's necessary for the string (or a unique hash) to be used in the mangling. This either requires linkers to handle arbitrarily-long symbol names (a problem even now) or for someone to pick a suitable hash function that has such a low probability of collision that even the ridiculously huge codebases C++ committee members have to care about would never hit a collision.

This is also the reason that floating-point values aren't supported. Floating-point values can be calculated differently based on all kinds of compile-time flags, but you'd need to ensure that foo<2.0 * 0.3> always mangled to the same value, even if compiled in two different translation units with different floating-point flags.

You likewise cannot template on addresses or pointers, as their locations change with each compile (or link, or run) and hence cannot be mangled consistently. Functions can be used as template arguments only in cases where the compiler can resolve them to a specific function and not just a function pointer, even in constexpr situations, since compilers typically just add the function's mangled name to the template's mangled name.

These problems are solvable but C++ imposed these rules many years ago. Nobody has written or submitted a paper to the ISO C++ committee to add solutions and update the rules.
 

But what could happen in a worse case scenario? If it was allowed, then, could it happen that 2 exact same instances of a template would be created(because a new template instance is created for every combination of template parameters used in code), so, would that somehow pose a problem?


Yes. See the One Definition Rule. It's the same as why you wouldn't want an inline class member function to be compiled in two different translation units and then not be handled by the linker, resulting in two definitions in final output image and letting you get two entirely different results for &my_class::my_function. The definitions must be unique, which at the least means they must mangle the same so that the linker can determine that the definitions are duplicates and throw out all but one of them.
 

I'm not sure if that'd actually work though - I don't know if templated arguments can take constexpr values.


They can. That's half the point of even having constexpr values.

#4 noatom   Members   -  Reputation: 782

Like
0Likes
Like

Posted 07 July 2014 - 03:20 AM

But I don't get a thing: why a simple constant global pointer won't be accepted, yet declaring that pointer with the external keyword, will make it work?

 

As far as I know, globals have program scope, so they aren't internally linked (per cpp file), so I don't see the problem.

 

the response:

A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage


Edited by noatom, 07 July 2014 - 03:55 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS