宏的單行定義
#define A(x) T_##x
#define B(x) #@x
#define C(x) #x
我們假設:x=1,則有:
A(1)------〉T_1
B(1)------〉'1'
C(1)------〉"1"
C++ Templates <The complete guide> 中的一個例子:
一個模板基類
template<class T>
class Base
{
public:
int field; // #1
};
派生類, 從上面的模板基類繼承
注意, 在此, 基類並不能確定就是上面的Base<T>,
因爲 下面#3 處可以看到, 程序對Base<int>進行了特化
template<class T>
class Derived : public Base<T>
{
public:
void f()
{
field++; //#2 哪個field? #1處還是#3處,
}
};
#2處的field到底是char還是int類型? 即#1處還是#3處 ? 顯然無法確定, 只有當
Derived被某個特定的T類型實例化的時候才知道.
template<>
class Base<int>
{
public:
char field; //#3
};
#2處的field是一個non-dependent name, 而基類Base<T>是一個dependent name, 因此不去其中查找.
正確的編譯器做法是: 在#1處報錯. VC7.1就是如此.
因此在Derived<T>模板類中, 如果確實需要指定Base<T>中的field, 應該使用 this->field 或者 Base<T>::field.