【问题标题】:Is there any way round to make this template specialisation link?有什么办法可以制作这个模板专业化链接吗?
【发布时间】:2014-12-05 18:44:46
【问题描述】:

我尝试了以下层次结构,但它没有链接。没有看到对c->Execute() 的调用,因为它似乎被Derived 中的Execute 所掩盖,并且找不到合适的类型来使用。我原以为如果有问题,它必须在编译时显示。我已经尝试在线使用 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;
}

【问题讨论】:

    标签: c++ templates specialization


    【解决方案1】:

    Derived&lt;TypeC&gt;::Execute() 必须定义,即使您从未调用它,因为您正在实例化类模板。尝试添加一个空定义,或者添加一个 throws 等,程序应该会按照您的预期链接和工作。

    【讨论】:

    • 添加您建议的专业化确实可以。非常感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2019-02-04
    • 2016-01-18
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多