【发布时间】:2011-01-03 15:53:52
【问题描述】:
以下代码 sn-p 对我有用:
class Foo {
public:
template <class T> T& get () { ... }
};
Foo foo;
foo.get<int>() = ...;
但是,下面的代码 sn-p 对我不起作用:
class Foo {
public:
template <class T> T& operator() () { ... }
};
Foo foo;
foo<int>() = ...;
错误是:
expected primary-expression before '>' token
expected primary expression before ')' token
两个错误都指向foo<int>()
为什么这不起作用,是否有可能解决这个问题?
【问题讨论】:
-
您的模板
operator()非常不可用,因为它的实例化只会在返回值上过载。继续使用get名称或类似名称。 -
它不是不可用的(尽管它可能不是更可取的)。请参阅下面的答案。
-
为什么要模板化函数而不是整个类?
-
@Zac,因为我不需要。我将它用于实体系统之类的东西,所以我可以这样做:
Entity entity = entitySystem.createEntity(); entitySystem.addTrait(entity, Position::id()); ... std::cout << entity.get<Position>().x;
标签: c++ templates operator-overloading