正如在这个问题中一样,我正在尝试使用 SBRM/RAII 通过一个类进行流式传输,所以
SBRM(x) << "test";
可以在析构函数中做一些额外的事情,但我的模板知识似乎有限。
我所拥有的(为了清楚起见而变得更简单)是:
#include <iostream>
#include <sstream>
class SBRM
{
public:
SBRM(int j) : i(j) {}
~SBRM() { std::cout << "SBRM(" << i << "): " << oss.str() << std::endl; }
template<typename T> SBRM& operator<<(T& in) { oss << in; return *this; }
// SBRM& operator<<(const long long& in) { oss << std::hex << "0x" << in; return *this; }
SBRM& operator<<(const double& in) { oss << in; return *this; }
SBRM& operator<<(const void* in) { oss << in; return *this; }
private:
int i;
std::ostringstream oss;
};
int main()
{
std::string ttt = "world";
const int i = 3;
SBRM(1) << "Hello";
SBRM(2) << ttt;
SBRM(3) << 0x1234567890123ll;
SBRM(4) << &i;
SBRM(5) << 5;
SBRM(6) << 0.23;
SBRM(7) << i;
SBRM(8) << 5 << ", " << ttt << ", " << &i;
}
这类作品:
SBRM(1): Hello
SBRM(2): world
SBRM(3): 3.20256e+14
SBRM(4): 0xbf8ee444
SBRM(5): 5
SBRM(6): 0.23
SBRM(7): 3
SBRM(8): 5, world, 0xbf8ee444
但我主要关心的是:为什么编译器要求我在使用(非字符串)文字时重载模板?
有什么技巧可以避免这种情况还是我采取了错误的方法?欢迎其他建议,因为我现在求助于使用宏
NOT_QUITE_SBRM_MACRO(3, "At least, " << 5 << ", this works");
gcc 4.1.2 出现了这个问题。和 4.4.3。没有重载函数,我得到:
sbrm-stream.cpp: In function ‘int main()’:
sbrm-stream.cpp:27: error: no match for ‘operator<<’ in ‘SBRM(3) << 320255973458211ll’
sbrm-stream.cpp:10: note: candidates are: SBRM& SBRM::operator<<(T&) [with T = long long int]
sbrm-stream.cpp:28: error: no match for ‘operator<<’ in ‘SBRM(4) << & i’
sbrm-stream.cpp:10: note: candidates are: SBRM& SBRM::operator<<(T&) [with T = const int*]
...