gpt4 book ai didi

c++ - VC6和模板错误

转载 作者:行者123 更新时间:2023-11-28 03:59:50 24 4
gpt4 key购买 nike

我正在重载运算符 << 来为类实现类似接口(interface)的流:

template<typename T>
CAudit& operator << ( const T& data ) {
audittext << data;
return *this;
}

CAudit& operator << ( LPCSTR data ) {
audittext << data;
return *this;
}

模板版本无法编译,出现“ fatal error C1001:内部编译器错误(编译器文件‘msc1.cpp’,第 1794 行)”。非模板函数都可以正确编译。

这是因为 VC6s 在处理模板时存在缺陷吗?有没有办法解决这个问题?

谢谢,帕特里克

编辑:

完整的类是:

class CAudit
{
public:
/* TODO_DEBUG : doesn't build!
template<typename T>
CAudit& operator << ( const T& data ) {
audittext << data;
return *this;
}*/

~CAudit() { write(); }//If anything available to audit write it here

CAudit& operator << ( LPCSTR data ) {
audittext << data;
return *this;
}

//overload the << operator to allow function ptrs on rhs, allows "audit << data << CAudit::write;"
CAudit& operator << (CAudit & (*func)(CAudit &))
{
return func(*this);
}

void write() {
}

//write() is a manipulator type func, "audit << data << CAudit::write;" will call this function
static CAudit& write(CAudit& audit) {
audit.write();
return audit;
}

private:
std::stringstream audittext;
};

问题出现在 operator << 的函数重载中,它用于允许 write() 被用作流操纵器:

CAudit audit
audit << "Billy" << write;

最佳答案

函数指针模板的重载对于旧的 Visual Studio 6 来说肯定是太多了。作为解决方法,您可以为您的操纵器定义一个类型并为该类型重载 operator<<。这是一些代码:

#include "stdafx.h"
#include <string>
#include <iostream>
#include <sstream>
#include <windows.h>

class CAudit {

std::ostringstream audittext;
void do_write() {}

public:
~CAudit() { do_write(); }

// types for manipulators
struct Twrite {};

// manipulators
static Twrite write;

// implementations of <<
template<typename T>
CAudit& operator << ( const T& data ) {
audittext << data;
return *this;
}

CAudit& operator << ( LPCSTR data ) {
audittext << data;
return *this;
}

CAudit& operator << ( Twrite& ) {
do_write();
return *this;
}
};

// static member initialization
CAudit::Twrite CAudit::write;



int main(int argc, char* argv[])
{
CAudit a;
int i = 123;
const char * s = "abc";

a << i << s << CAudit::write;

return 0;
}

关于c++ - VC6和模板错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1388230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com