1
我已經嘗試過以下的層次結構,它沒有鏈接。 c->Execute()
的呼叫沒有被看到,因爲它似乎被Execute
在Derived
中掩蓋,並且它找不到適當的類型來使用。我會認爲如果出現問題,它將不得不在編譯時顯示。我已經使用GCC 4.8在線以及Windows上的borland編譯器進行了嘗試。這兩種情況下的錯誤消息都是相似的。東西的順序:有沒有什麼辦法使這個模板專業化鏈接?
/tmp/ccrT5mNy.o:(.rodata._ZTV7DerivedI5TypeCE[_ZTV7DerivedI5TypeCE]+0x10): undefined reference to `Derived<TypeC>::Execute()'
collect2: error: ld returned 1 exit status
我會非常感謝任何指針。
#include <iostream>
class BaseType
{
public:
BaseType() {}
virtual void Execute() { std::cout << "BaseType execute..." << std::endl; };
protected:
};
struct TypeA;
struct TypeB;
struct TypeC;
class Derived2 : public BaseType
{
public:
Derived2() : BaseType() {}
virtual void Execute() { std::cout << "Derived execute2" << std::endl; }
protected:
};
template <typename T>
class Derived : public BaseType
{
public:
Derived() : BaseType() {}
virtual void Execute();
protected:
};
template <typename T>
class GrandChild : public Derived<T>
{
public:
GrandChild() : Derived<T>() {}
void Execute();
};
template<>
void Derived<TypeA>::Execute() { std::cout << "Derived execute... TypeA" << std::endl; }
template<>
void Derived<TypeB>::Execute() { std::cout << "Derived execute... TypeB" << std::endl; }
template<>
void GrandChild<TypeC>::Execute() { std::cout << "Derived execute... TypeC" << std::endl; }
int main()
{
BaseType* a = new Derived<TypeA>();
BaseType* b = new Derived<TypeB>();
BaseType* c = new GrandChild<TypeC>();
BaseType* d2 = new Derived2();
a->Execute();
b->Execute();
c->Execute();
d2->Execute();
delete a;
delete b;
delete c;
delete d2;
}
它通過添加您建議的專業化肯定會工作。非常感謝您的答覆。 – 2014-12-09 12:18:22