Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

address of c++ template function

Why does this fail to compile? (g++-4.5)

template < typename U >
static void h () {
}

int main () {
  auto p = &h<int>; // error: p has incomplete type
}

EDIT: Here is a work-around:

template < typename U >
static void h () {
}

int main () {
  typedef decltype (&h<int>) D;
  D p = &h<int>; // works
}
like image 428
Thomas Avatar asked Sep 04 '10 09:09

Thomas


People also ask

What is the function of a template?

Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Generic Programming is an approach to programming where generic types are used as parameters in algorithms to work for a variety of data types.In C++, a template is a straightforward yet effective tool.

How do you call a function template?

Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.

What is the need of template functions in C?

This template allows the code needed to define variables with basic type to be generalized and abstracted. The goal is to make code sharable and similar between types.

What is the use of template in C++?

A template is a simple yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types.


1 Answers

In C++0x this is guaranteed to work. However in C++03 this wasn't working (the initializer part, that is) and some compilers apparently don't support it yet.

Furthermore, I remember that the C++0x wording is not clear what happens with &h<int> when it is an argument to a function template and the corresponding parameter is deduced (this is what auto is translated to, conceptionally). The intention is, however, that it is valid. See this defect report where they designed the wording, the example by "Nico Josuttis" and their final example.

There is another rule that the wording enforces but compilers are not correctly implementing. For example, see this clang PR.

like image 65
Johannes Schaub - litb Avatar answered Sep 18 '22 12:09

Johannes Schaub - litb