• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
noatom

Template non type parameters question

3 posts in this topic

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?

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0