With
template <typename T>
class Foo {
public:
template <int x>
void bar () {}
};
the following compiles:
void fooBar ()
{
Foo<int> f;
f.bar<1>();
}
but the following does not (with "error: expected primary-expression before ')' token" in gcc 5.4.0 with -std=c++14).
template <typename T>
void fooBar ()
{
Foo<T> f;
f.bar<1>();
}
If I try to explicitly call the second version, with e.g.
fooBar<int>();
then gcc additionally complains about
"invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'".
Is there any reason why the second version is invalid? Why is gcc treating the '<' as an operator rather than the beginning of a template parameter list?
Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter (s) inside <> which is followed by the class declaration.
In this tutorial, we will learn about class templates in C++ with the help of examples. Templates are powerful features of C++ which allows us to write generic programs. There are two ways we can implement templates: Similar to function templates, we can use class templates to create a single class to work with different data types.
C++ Function Template 1 Function Template Declaration. A function template starts with the keyword template followed by template parameter (s) inside <> which is followed by function declaration. 2 Calling a Function Template. We can then call it in the main () function to add int and double numbers. 3 Example: Finding the Absolute Value of Numbers
Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter (s) inside <> which is followed by the class declaration.
With the templated function, the compiler doesn't know exactly what Foo<T>
will be (there could be specializations of Foo
), so it it has to assume that f.bar
is a member variable and parse the code as
f.bar < 1
and then it cannot continue.
You can help the compiler by telling it that bar
is a template
f.template bar<1>();
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