C++ происходит из собственного типа

Вам следует попробовать boost :: exception

Цель Boost Exception - упростить разработку иерархий классов исключений и помочь в написании кода обработки исключений и отчетов об ошибках.

Он поддерживает передачу произвольных данных на место улова, что в противном случае сложно из-за требований отсутствия бросков (15.5.1) для типов исключений. Данные могут быть добавлены к любому объекту исключения, либо непосредственно в throw-выражении (15.1), либо позже, когда объект исключения распространяется по стеку вызовов.

Возможность добавлять данные к объектам исключений после того, как они были переданы для выброса, важна, потому что часто некоторая информация, необходимая для обработки исключения, недоступна в контексте, где обнаружен сбой.

Boost Exception также поддерживает копирование объектов исключений в стиле N2179, реализованное незаметно и автоматически с помощью функции boost :: throw_exception.

7
задан SPWorley 26 July 2009 в 02:03
поделиться

4 ответа

Something like this...

template <typename T> class logging_type
{
private:
   T value;
public:
   logging_type() { }
   logging_type (T v) : value(v) { }  // allow myClass = T
   operator T () { return value; }  // allow T = myClass
   // Add any operators you need here.
};

This will create a template class that's convertible to the original type in both directions. You'd need to add logging handling and overload operators for every operation used on that type in your code.

This still might not be quite what you want, because it's implicitly convertible to int (or whatever type you specify), so your code might silently convert your logging int to an int and you'd be left with incomplete logs. You can prevent this in one direction by adding an 'explicit' keyword to the constructor, but you can't do anything similar with the conversion operator. Unless you perhaps make it private... I haven't tried. Doing either of those things will somewhat defeat the purpose though.

Edit: Since c++11, you can add explicit to conversion operators.

8
ответ дан 6 December 2019 в 10:02
поделиться

This is actually one case where #define is very helpful. I recommend

#ifdef DEBUG
#    define INTGR MyDebugIntegerClass
#else
#    define INTGR int
#endif

Make sure that MyDebugIntegerClass can cast itself to a regular int, and has all appropriate operators. Then, write your code with INTGR.

In debug mode, you'll get all the logging of your class, but in release mode, you'll get a plain-basic int.

3
ответ дан 6 December 2019 в 10:02
поделиться

вы никогда не сможете наследовать от примитивных типов

-1
ответ дан 6 December 2019 в 10:02
поделиться

You can't derive a class from int, but you should be able to make a class (e.g. Integer) that is interchangeable with int by implementing Coplein's Concrete Data Type idiom from Advanced C++: Programming Styles and Idioms and then by overloading the type cast operator from Integer to int and defining a conversion operator from int to Integer.

here is another link that describes the basic Idioms from the book

and yet another link that I think is pretty close to what you are looking for http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Int-To-Type

9
ответ дан 6 December 2019 в 10:02
поделиться
Другие вопросы по тегам:

Похожие вопросы: