【问题标题】:Can I pass a non-type template argument to an overloaded operator?我可以将非类型模板参数传递给重载运算符吗?
【发布时间】:2012-02-02 16:16:35
【问题描述】:

我想通过重载 () 作为 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&lt;3&gt;(); 被注释掉,这将按预期编译和运行。 C++ 语法是否支持我正在尝试做的事情,还是我应该放弃并坚持使用 getter 的命名方法?

【问题讨论】:

  • 我现在无法证明这一点,但我确信唯一的方法是foo.operator()&lt;3&gt;(),这可能会破坏目的。

标签: c++ templates operator-overloading


【解决方案1】:

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

foo.operator()<3>();

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

【讨论】:

    【解决方案2】:

    您可以像这样将模板放在类上来管理:

    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 中有很多其他的东西,所以将模板移动到类(这可能是一个重大的设计更改)可能是不可接受的,只是为了管理它。

    编辑:

    实际上,因为可能已经有一个 Foo 的实例,OP 正在使用,所以我的整个提议是愚蠢的。不要打扰。

    【讨论】:

    • 我完全同意你的观点,将模板移动到课堂上可能是不可接受的。不是因为完成一项小任务的代价太大,而是因为它无法完成任何事情
    猜你喜欢
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多