Aug 19, 2018

[C++20] String literals as non-type template parameters

Follow up with previous post and why the 'WTH?!" :-P
http://vsdmars.blogspot.com/2018/08/c20-compile-time-regex.html


Background knowledge:

7.5.1 Literals [expr.prim.literal]
1 #A literal is a primary expression. Its type depends on its form. A string literal is an lvalue; all other literals are prvalues.

i.e const char* _ = "XXX"

Template non-type arguments can't be internal linkage pointer, in this proposal, the implement becomes: (excerpt from pdf)

The idea behind how this would work is that the compiler would generate a constexpr array and pass a reference to that as a template argument:
template <auto& str>
void f()
{ 
// str is a 'char const (&)[7]'
} 

f<"foobar">(); // should be roughly equivalent to inline constexpr char

__unnamed[] = "foobar";

f<__unnamed>();

Calling a function template with such a template-parameter-list works in both Clang and GCC today.
---------
Once it becomes char [] in a TU, it's location is settled at compile time,
thus, template can be instantiated~~~
Nice~

What about ODR?

If it's instantiated in the .cpp, there's no ODR violation due to difference address of pointer generated different type of template instance(name mangled)

If it's instantiated in the .h, the proposal suggests 'should not be an ODR violation' since it's inlined thus with external linkage thus with one single instance of the template being instantiated.


Once again, compatible to C having all this interesting, auh, engineering work around. :-p

Reference:

[C++] char string literal is l-value

P0424R2 Louis Dionne & Hana Dusíková

Compiler tool chain linking notes

[C][C++] difference between char array[] and char *array, why char [] not char* could be used in non-type argument for template.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.