Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of C++11 template parameter misbind?

Tags:

In 6.8.3 of the C++11 standard it says:

If, during parsing, a name in a template parameter is bound differently than it would be bound during a trial parse, the program is ill-formed.

What is an example of a program that is ill-formed as a result of this requirement?

like image 684
Andrew Tomazos Avatar asked Apr 11 '13 06:04

Andrew Tomazos


People also ask

Which is correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.

How do you pass a parameter to a template in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Why do we use :: template template parameter?

8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.

What is non-type template parameters?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.


1 Answers

#include <iostream> #include <typeinfo>  typedef const int cint;  template <int a> struct x {   static cint b = 0; };  template <> struct x<42> {   typedef cint b; };  cint w = 17;  int main () {   cint (w)(42), (z)(x<w>::b);    std::cout << typeid(z).name() << std::endl; } 

The first declaration in main() needs to be disambiguated, so a trial parse is performed. During this parse, the local w is unknown, since the parse is purely syntactic (things are only parsed, no semantic actions are performed). Consequently, w is a global constant, its value is 17, x<w>::b is a value, and z is a variable.

During the real parse, semantic actions take place. Thus the name w is bound to the freshly declared local constant, its value is 42, x<w>::b becomes a type, and z is a function declaration.

like image 113
n. 1.8e9-where's-my-share m. Avatar answered Oct 11 '22 01:10

n. 1.8e9-where's-my-share m.