Вопрос

Я перегружаю оператор << для реализации потока, как интерфейс для класса:

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

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

Версия шаблона не может компилироваться с «фатальной ошибкой 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;
};

Проблема возникает при перегрузке функции оператора <<, которая используется для использования write () в качестве манипулятора потока:

CAudit audit
audit << "Billy" << write;
Это было полезно?

Решение

Эта перегрузка шаблона для указателей функций, безусловно, слишком много для старой старой визуальной студии 6. В качестве обходного пути вы можете определить тип для вашего манипулятора и оператора перегрузки << для этого типа. Вот какой -то код:

#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;
}

Другие советы

Вид ошибки определенно выглядит как вид сбоев, вызванные предварительной стандартной реализацией шаблонов VC6.

Лучший совет - это, конечно, для обновления до VC7.0, 7.1, 8.0, 9.0 или бета -версии 10. Чтобы сравнить это с версиями Windows, он все еще использует Windows 98, когда доступны Me, 2000, XP, Vista и 7.

Сказав это, вы можете много упростить поиск с помощью простого трюка:

class CAudit {
    template<typename T>
    CAudit& operator<<(T const& t) {
        this->print(t);
        return *this;
    }
private:
    void print(int);
    void print(LPCSTR);
    void print(CAudit & (*func)(CAudit &));
    template<typename T> print(T const&);
};

Надежда здесь в том, что первый поиск operator<< Находит шаблон единого элемента. Другой operator<< Кандидаты являются не членами для других классов и встроенных встроенных. Они должны быть однозначно хуже, чем этот шаблон. Второй взгляд внутри вашего operator нужно иметь дело с CAudit члены позвонили print.

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

РЕДАКТИРОВАТЬ:

#include <iostream>
using namespace std;

class CAudit{
public:
    CAudit(){}

    template< typename T >
    CAudit &operator<<(T arg);
    CAudit &operator<<(char s);
};

template< typename T>
void oldLog(T arg){
  cout << arg;
}

template< typename T >
CAudit &CAudit::operator<<(T arg){
    oldLog( arg );
    return *this;
}
CAudit &CAudit::operator<<(char arg){
    oldLog( arg );
    return *this;
}
int main(){

    CAudit e;
    e << "Hello";
    e << 'T';

 return 0;
}

Проблема, кажется, не в том, что вы разместили кодовой фрагмент. Эта программа работает нормально:

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

class CAudit {

std::ostringstream audittext;

public:
std::string getAuditText() const { return audittext.str(); }

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


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

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


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

a << i;
a << s;

std::cout << "audittext is: '" << a.getAuditText() << "'\n";
return 0;
}

Не могли бы вы опубликовать еще код?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top