我相信这里的标题可以更具体,所以我鼓励任何有更好想法的人更改它。同时,我会尽力把问题弄清楚。
我有一些像这样的抽象包装类:
class Attribute{
public:
static const std::string name;
Attribute() {
virtual ~Attribute() {}
virtual void calculateAttribute() = 0;
}
template <typename AttType> class TypedAttribute: public Attribute{
public:
static const std::string name;
TypedAttribute() {}
virtual ~TypedAttribute() {}
virtual void calculateAttribute() = 0;
AttType &value();
}
之后,具体属性继承自TypedAttribute
,例如:
class AreaAttribute : public TypedAttribute<int> {
public:
static const std::string name = "area";
...
}
class EntropyAttribute : public TypedAttribute <double> {
public:
static const std::string name = "area";
...
}
最后,我有一个模板化函数,它应该为一系列值找到一个最大值(最初是最小值和最大值,但为了简洁起见)属性,如下所示:
template <typename TAT>
int Node::minAttribute(const std::vector <MyObject *> &items) const{
// all attributes always positive scalar values
int minVal = -1;
for (int i=0; i < (int)items.size(); ++i)
int v = ((TAT *)items[i]->getAttribute(TAT::name))->value();
if (minVal == -1 || v < minVal)
minVal = v;
return minVal;
}
附有使用范例minAttribute<AreaAttribute>(myItems);
但是,这样做并不能让我知道 TypedAttribute
是如何产生的是输入的,我被迫总是返回 int
值(value)。有没有办法访问 TypedAttribute
的类型以前可以模板化函数的返回值吗?像这样(我知道这种语法不起作用):
template <typename TYP>
template <class TypedAttribute< TYP > TAT>
TYP minAttribute(const std::vector <MyObject *> &items) const{
// example line:
TYP v = ((TAT *)items[i]->getAttribute(TAT::name))->value();
}
最佳答案
typedef 或在您的 TypedAttribute 类中使用将使该类可用。
template <typename AttType>
class TypedAttribute: public Attribute
{
public:
using AttributeType = AttType;
//can use a typedef for older versions of C++
//...
};
然后利用这个改变你的 minAttribute 函数来返回那个类型:-
template <typename TAT>
typename TAT::AttributeType Node::minAttribute(const std::vector <MyObject *> &items) const
{
// can return TAT::AttributeType instead of int
// will need a < operator than can be used with TAT::AttributeType
}
关于c++ - 我可以访问嵌套模板 C++ 的类型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37002534/