我想创建一个具有成员变量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;
}
答案 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;
}
};