問題:我需要找到修改結構成員的時間和位置。
我在一個大型實時系統上作業,其中一些舊系統最初是用 C 撰寫的。在這種情況下,結構從來不是類,也沒有私有成員,所以一切都在微風中飄揚。
我有很好的分析和除錯工具,但是一個結構成員的設定避開了靜態分析,gdb watch 很困難,因為我們有太多的結構實體。在實時系統上運行 gdb 也會產生奇怪的結果。
這是我用來將成員宣告更改為int將報告分配的模板實體的模板。除了兩種情況外,這在所有情況下都有效。
- 我無法撰寫允許將模板的值轉換為列舉的多載(我可以將其轉換為浮點數)。這是通過添加 * 解決的,從而強制使用 * 運算子。但是,如果我能宣告一個可以避免這種情況的多載,那就再好不過了。幸運的是,代碼中只有一個實體。請參閱下面的錯誤。
- 最初我有一個我認為是參考運算子的東西
T& operator&(),但最終在寫這篇文章時發現這operator T& ()是正確的解決方案。為什么第一個不起作用?
#include <stdio.h>
template <typename T> class TraceType {
private:
T value;
public:
TraceType() { value = (T)~0; }
T operator=(T v) { notify(v); value = v; return v; }
T operator->() const { return value; }
T operator*() const { return value; }
operator T& () { return value; }
operator T () const { return value; }
bool operator==(const T rhs) const
{ return value == rhs; }
void notify(T);
};
struct Foo {
int x;
// this should have been the only change necessary
// need to find when/where this gets changed
// int y;
TraceType<int> y;
int z;
};
const char* getStackTrace() { return "<stack trace"; }
template<> void TraceType<int>::notify(int v)
{ printf("y<--%d %s\n", v, getStackTrace()); }
enum Special { one, two, three };
int main(int argc, char** argv)
{
Foo foo;
foo.x = 1;
foo.y = 2;
foo.z = 3;
Foo* fooPtr = &foo;
// error: invalid cast from type ‘TraceType<int>’ to type ‘Special’
// Special xxx = (Special)fooPtr->y;
Special xxx = (Special)*fooPtr->y; // this works
float yyy = (float)fooPtr->y; // this works
int& refToY = foo.y; // this works
}
uj5u.com熱心網友回復:
添加模板化轉換運算子:
template <typename T> class TraceType {
private:
T value;
public:
TraceType() { value = (T)~0; }
T operator=(T v) { notify(v); value = v; return v; }
T operator->() const { return value; }
T operator*() const { return value; }
operator T& () { return value; }
operator T () const { return value; }
bool operator==(const T rhs) const
{ return value == rhs; }
// Templated conversion operator
template <class U> operator U() const { return static_cast<U>(value); }
void notify(T);
};
uj5u.com熱心網友回復:
關于您實作的嘗試:T& operator&()...
operator&()(不帶引數)是運算子的地址。
通常,您不應多載 address-of 運算子。
但是,如果您這樣做,則讓它回傳所表示物件的地址。
T * operator & () { return &value; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364602.html
