C ++ function objects with explicit template parameters

I have a function object with an explicit (i.e. not deduced) template parameter defined as follows:

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 compilation error. Is it impossible to call a function object with a template parameter, like a regular function? I really need to have it as a function object. Making a free feature is actually not an option for me (or at least it's a very dirty option).

+5
source share
3 answers

Unfortunately, you cannot call that. You need to use the syntax operator():

int i = bar.operator()<int>();
+9
source

You can use the conversion operator trick as follows:

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

foo bar = {};
int main()
{
  int i = bar(); // implicit
  auto x = static_cast<int>(bar()); // "explicit" template parameter
}

, bar<int>() .

+2

Perhaps you can simplify your decision as follows:

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

foo<int> bar = {};

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

All Articles