Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function objects with explicit template parameters

Tags:

c++

c++11

boost

I have a function object with an explicit(ie non-deduced) template parameter defined like this:

struct foo
{
    template<class T>
    T operator()() const
    {
        return 5;
    }
};

foo bar = {};

When I try to call it like this:

int main()
{
    int i = bar<int>();
    return 0;
}

I get a compile error. Is there no way to call the function object with a template parameter like a regular function? I really need to have it as a function object. Making a free function is not really an option for me(or at least, it is a very messy option).

like image 544
Paul Fultz II Avatar asked Feb 21 '13 22:02

Paul Fultz II


People also ask

Can we pass Nontype parameters to templates?

Template classes and functions can make use of another kind of template parameter known as a non-type parameter. 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.

Can template have default parameters?

Template parameters may have default arguments. The set of default template arguments accumulates over all declarations of a given template.

Can a template be a template parameter?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)

Which template can have multiple parameters?

C++ Templates: Templates with Multiple Parameters | C++ Tutorials for Beginners #65.


1 Answers

Unfortunately, you can't call it like that. You need to use the operator() syntax:

int i = bar.operator()<int>();
like image 198
Joseph Mansfield Avatar answered Oct 16 '22 04:10

Joseph Mansfield