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
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With