此代码如何不编译?为什么不能将bs[1]
推导为bool
?
是否有解决此问题的通用方法?
#include <iostream>
#include <string>
#include <bitset>
using namespace std;
template<typename T> struct StringConverter{};
template<> struct StringConverter<bool>{
std::string operator()(const bool &i){ return i?"true":"false"; }
};
template<typename T> std::string to_string(const T &val){
return StringConverter<T>()(val);
}
int main(){
// this does not compile
std::bitset<10> bs;
std::cout << to_string(bs[0]) << std::endl;
// this does
const std::bitset<10> bs_const;
std::cout << to_string(bs_const[0]) << std::endl;
}
编译器错误:
main.cpp:12:12: error: type 'StringConverter<std::bitset<10>::reference>' does not provide a call operator
return StringConverter<T>()(val);
^~~~~~~~~~~~~~~~~~~~
main.cpp:18:18: note: in instantiation of function template specialization 'to_string<std::bitset<10>::reference>' requested here
std::cout << to_string(bs[0]) << std::endl;
^
1 error generated.
最佳答案
非常量bitset::operator []返回一个代理对象而不是 bool(boolean) 对象(必须这样做,因为可以使用该代理来更改位值)。 const bitset::operator []但是只返回 bool(boolean) 值(不是引用,只是普通 bool(boolean) 值),因此它与StringConverter [