模板类spezialisation缺少成员

时间:2016-02-17 10:14:30

标签: c++ templates

我想创建一个具有成员变量ret的简单模板类。出于某种原因,我的MSVC 2010编译器抱怨说,ret中没有名为Converter<double>的声明变量。我真的很无能,为什么?

template<typename M>
struct Converter  {
    M ret;

    void operator()(const int& value) {
        throw std::exception("Not implemented!");
    }
};

template<>
struct Converter<double> {
    void operator()(const int& value) {
        ret=value;
    }
};

int main() {
    Converter<int> x;
}

2 个答案:

答案 0 :(得分:2)

这是另一个类(这里没有继承或任何其他依赖性):

template<>
struct Converter<double> {
    double ret;
    void operator()(const int& value) {
        ret=value;
    }
};

答案 1 :(得分:1)

我知道这已经解决了,但我想我应该进一步澄清这一点。 Converter<double>Converter<int>是不同的单独类,因此在您将其声明为其成员之一之前,不会在双重变体中定义ret

无论如何,你想要实现的是继承,这可以通过类似的方式完成:

template<typename M>
struct AbstractConverter  { // you could call it 'Converter' too, and it'll work as you expect
    M ret;

    virtual void operator()(const int& value) {
        throw std::exception("Not implemented!");
    }
    //or 
    virtual void operator(const int &value) = 0; //pure virtual
    // will not compile if someone wants to use it directly
};

template<>
struct Converter<double> : public AbstractConverter<double>{
    void operator()(const int& value) { // we implement the operator here
        ret=value;
    }
};