【发布时间】:2012-08-24 22:02:30
【问题描述】:
有这样的代码。
const std::string DeviceTypeStrings[] ={ "A", "B", "C", "D", "E" };
enum DeviceTypes { A = 0, B, C, D, E };
template <DeviceTypes T> class DeviceType;
template <DeviceTypes T> std::ostream& operator<< (std::ostream& output, const DeviceType<T>& dev);
template <DeviceTypes T> class DeviceType {
public:
static const int value = T;
static const std::string string;
friend std::ostream & operator<< <>(std::ostream & output, const DeviceType<T> & deviceType );
};
template <DeviceTypes T> const std::string DeviceType<T>::string = DeviceTypeStrings[T];
template <DeviceTypes T> std::ostream & operator<< (std::ostream & output, const DeviceType<T> & deviceType ){
if ( DeviceType<T>::string.find(' ') != std::string::npos ){
return output << "\"" << DeviceType<T>::string << "\"";
} else {
return output << DeviceType<T>::string;
}
}
int main () {
DeviceType<A> myType;
std::cout << myType << std::endl;
return 0;
}
注意在DeviceType类的”,“”是什么意思?如果可以,为什么它必须在那里?
【问题讨论】:
-
它可以编译吗?在我看来是个错误。
-
它会编译。语法上是正确的。
-
@PeteBecker:- OP 是一个
Negative Zero,所以一定已经编译了 ;) -
如果我把模板参数中的
DeviceTypes改成class,it compiles。我假设他有一个以 C++ 概念作为扩展的编译器? -
附上完全编译的代码。