c++ - 我可以访问嵌套模板 C++ 的类型吗

标签 c++ templates

我相信这里的标题可以更具体,所以我鼓励任何有更好想法的人更改它。同时,我会尽力把问题弄清楚。

我有一些像这样的抽象包装类:

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/

相关文章:

javascript - 我如何创建像这个网站一样的文字? (CSS/JavaScript)

c++ - 编译 C++ 模板代码时出现问题

c++ - Qt 中可调整大小的布局/框架,每个小部件由用户

c++ - 具有多个枚举的C++运行时类型切换

c++ - 为什么 WS_TABSTOP 不适用于丰富的编辑控件?

c++ - 使用 boost::asio::async_read 失败但 boost::asio::read 有效(我正在使用 io_stream.run_one())

c++ - 在模板参数推导过程中丢失限定符

c++ - 递归类型的模板特化

c++ - 错误 : expected ';' before '<' token

c++ - 从通过指针取消引用从 C 函数调用的 C++ 函数中抛出