我可以将非类型模板参数传递给重载运算符吗?

时间:2012-02-02 16:16:36

标签: 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;
}

如果注释掉foo<3>();,则会按预期编译并运行。 C ++语法是否支持我正在尝试做的事情,或者我应该放弃并坚持使用getter的命名方法?

2 个答案:

答案 0 :(得分:8)

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

foo.operator()<3>();

所以,坚持使用命名函数。

答案 1 :(得分:0)

您可以通过将模板放在类上来进行管理:

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

    static void Get()
    {
        std::cout << "called get() with " << i << std::endl;
    }
};

int main()
{
    Foo<1>::Get();
    Foo<3>();
    return 0;
}

然而,在调用direct()表单时,您将构造一个Foo对象,但是会有一点损失。

另外,我猜你的现实代码在Foo类中有很多其他的东西,所以将模板移动到类(这可能是一个重大的设计更改)可能是不可接受的,只是为了管理它。

编辑:

实际上由于OP可能已经有一个Foo实例,我的整个建议都是愚蠢的。不要打扰。