我想通过重载()作为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>()',这可能会失败的目的。 – PlasmaHH 2012-02-02 16:20:07