C ++模板类专门化:为什么通常的方法需要重新实现 [英] C++ template class specialization: why do common methods need to be re-implemented

查看:234
本文介绍了C ++模板类专门化:为什么通常的方法需要重新实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在示例中:

  #include< iostream> 

using namespace std;

class B
{
public:
virtual void pvf()= 0;
};

template< class T>
class D:public B
{
public:
D(){}

virtual void pvf(){}

private:
string data;
};

模板<>
class D< bool> :public B
{
public:
D();

virtual void pvf(){cout< bool type< endl }
};

int main()
{
D< int> d1;
D< bool> d2;
}

我收到以下错误:

  test.cpp :(。text + 0x1c):未定义引用`D< bool> :: D()'
请注意,我不是专门研究D()本身的原因是我想要消除对字符串<$ c $的需要,这是因为我不需要使用字符串<$ c $ p

<在 D 案例中的 < T> :: data 。



为什么我需要在 D< bool> 中重新实现 D()?似乎应该有一种方法让我告诉编译器使用 D< T> 的版本。



有没有办法做这样的简单的专业化,而不必重新实现方法?

解决方案



专业化与继承行为非常不同。它没有与通用模板版本的连接。



当您使用/实例化模板时,编译器将创建一个新的类型名称,然后查找这个类型定义。当它找到一个特殊化,那么​​它作为新类型的定义。当它不是,它需要通用模板并实例化它。



因此,他们没有连接,你只是写一个全新的类,只是一个特殊的名称以便编译器在有人使用/实例化模板的情况下查找该名称。


In the sample:

#include <iostream>

using namespace std;

class B
{
public:
    virtual void pvf() = 0;
};

template <class T>
class D : public B
{
public:
    D(){}

    virtual void pvf() {}

private:
    string data;
};

template <>
class D<bool> : public B
{
public:
    D();

    virtual void pvf(){ cout << "bool type" << endl; }
};

int main()
{
    D<int> d1;
    D<bool> d2;
}

I get the following error:

test.cpp:(.text+0x1c): undefined reference to `D<bool>::D()'

Note that the reason I don't just specialize the D() by itself is I want to eliminate the need for string D<T>::data in the D<bool> case.

Why do I need to re-implement D() in D<bool>? Seems like there should be a way for me to tell the compiler to use the version from D<T>.

Is there any way to do a simple specialization like this without having to re-implement methods?

解决方案

No, there is not.

Specialization is behaving very differently than inheritence. It has no connection to the generic template version.

When you use/instantiate a template, the compiler will create a new type name, and then look for how this type is defined. When it finds a specialization, then it takes that as the definition for the new type. When it does not, it takes the generic template and instantiates it.

Therefore they have no connection, and you are just writing an entirely new class, just with a special name for the compiler to find in case of someone using/instantiating the template to find it under that name.

这篇关于C ++模板类专门化:为什么通常的方法需要重新实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆