Ben*_*Kay 5 c++ templates operator-overloading
我想通过重载()作为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;
}
Run Code Online (Sandbox Code Playgroud)
如果foo<3>();被注释掉,这将按预期编译和运行.C++语法是否支持我正在尝试做的事情,或者我应该放弃并坚持使用getter的命名方法?