Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templated function in templated class [duplicate]

Tags:

c++

gcc

templates

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?

like image 897
Matt Avatar asked May 25 '17 11:05

Matt


People also ask

What is the difference between function template and class template?

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.

What are class templates in C++?

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.

How to use function template in C++ with example?

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

What are the advantages of using a class template?

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.


1 Answers

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>();
like image 147
Bo Persson Avatar answered Oct 23 '22 18:10

Bo Persson