我想通过重载()作为getter方法向类中添加一些语法糖。但是,getter方法采用非类型模板参数。考虑一个简单的测试用例:

#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;
}

如果将foo<3>();注释掉,它将编译并按预期运行。 C++语法是否支持我要执行的操作,还是应该放弃并坚持使用用于getter的命名方法?

最佳答案

您正在寻找的语法存在,但是您不喜欢它:

foo.operator()<3>();

因此,请坚持使用命名函数。

10-08 08:28
查看更多