Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a non-type template argument to an overloaded operator?

I would like to add some syntactic sugar to a class by overloading () as a getter method. However, the getter method takes a non-type template argument. Consider a simple test case:

#include <iostream>

class Foo
{
public:
  template <int i> void get()
  {
    std::cout << "called get() with " << i << std::endl;
  }
  template <int i> void operator()()
  {
    std::cout << "called overloaded () with " << i << std::endl;
  }
};

int main()
{
  Foo foo;
  foo.get<1>();
  foo.get<2>();
  foo<3>(); // error: no match for ‘operator<’ in ‘foo < 3’
  return 0;
}

This compiles and runs as expected if foo<3>(); is commented out. Does C++ syntax support what I'm trying to do, or should I just give up and stick with a named method for the getter?

like image 997
Benjamin Kay Avatar asked Feb 02 '12 16:02

Benjamin Kay


1 Answers

The syntax you're looking for exists, but you won't like it:

foo.operator()<3>();

So, stick with the named function.

like image 197
Armen Tsirunyan Avatar answered Sep 30 '22 04:09

Armen Tsirunyan