2012-02-02 67 views
5

我想通过重载()作为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的命名方法?

+1

我现在无法证明它,但肯定唯一的办法是'foo.operator()<3>()',这可能会失败的目的。 – PlasmaHH 2012-02-02 16:20:07

回答

8

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

foo.operator()<3>(); 

所以,坚持使用命名的功能。

+0

@轨道上的亮度比赛:从不知道 – noisy 2012-02-02 16:26:53

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

然而,有一个小的损失,因为调用直接()的形式时,你会构造一个Foo对象。

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

编辑:

实际上,因为有可能已经是,OP是使用美孚的情况下,我的整个的建议是愚蠢的。不打扰。

+0

我完全同意你的看法,将模板移动到课堂上可能是不可接受的。不是因为完成一项小任务的代价太大,而是因为它不能完成*任何事情* – 2012-02-02 16:32:15

相关问题