简体   繁体   English

C ++部分模板专业化

[英]C++ partial template specialization

Is this answer considered "good" code or is it just an ugly hack? 这个答案被认为是“好”的代码还是只是一个丑陋的黑客?

And I would like to know how this is forward-declared (both classes). 而且我想知道这是如何向前声明的(两个类)。

When I just forward-declare the class with 2 template-parameters, it just always takes this one, no matter what value flag has. 当我只使用2个模板参数向前声明类时,无论有什么值flag ,它都只需要这个参数。

I would like to do this because I have 2 special member functions which should behave differently on flag being true and I don't feel like reimplementing the whole class. 我想这样做是因为我有2个特殊的成员函数,这些函数在flag为true时表现不同,我不想重新实现整个类。 Also, it should have the same name. 另外,它应该具有相同的名称。 According to this example, this seems to be possible. 根据这个例子,这似乎是可能的。

And I have to forward-declare it because I'm creating a library in which we forward-declare everything. 我必须向前声明它,因为我正在创建一个库,我们在其中向前声明所有内容。

Any idea? 任何想法?

It has the drawback that it doesn't really work. 它有一个缺点,那就是它不能真正起作用。 The base member function is not overridden, but it is just hidden by the derived class' function when you try to call it from outside. 不会覆盖基本成员函数,但是当您尝试从外部调用它时,它只是被派生类的函数隐藏。 Which means if you call doSomething out of the base class (where presumably all your other functions live) it will call the base class doSomething which is not what is wanted. 这意味着如果你从基类中调用doSomething (可能你所有其他函数都存在),它将调用基类doSomething ,这不是你想要的。

The accepted answer on that question shows multiple ways for how you can solve your problem. 在该问题上接受的答案显示了解决问题的多种方法。

In order to use specialisation its definition always has to be visible to the caller. 为了使用特化,其定义始终必须对调用者可见。 If, for example, you have template <class Type, bool flag> struct something defined in one header and template <class Type> struct something<Type, true> : public something<Type, false> defined in the second one, to use the latter you have to include the second header . 例如,如果你有template <class Type, bool flag> struct something在一个头文件和template <class Type> struct something<Type, true> : public something<Type, false>定义的template <class Type, bool flag> struct something template <class Type> struct something<Type, true> : public something<Type, false>在第二个中定义,使用后者你必须包括第二个标题 Without that you will always get the first, more generic type. 否则,您将始终获得第一个更通用的类型。

EDIT: the bit about forward-declaring got me thinking. 编辑:关于向前声明的一点让我思考。 If you want to use only type declaration, as in pointer variable, do the following: 如果要仅使用类型声明,如在指针变量中,请执行以下操作:

Header

template <class Type, bool flag>
struct something;

struct Test
{
    something<int, true>* ptr; // definition not needed
    Test();
}

Source 资源

#include "something.h" // header with template
#include "something_spec.h" // header with specialisation

Test::Test()
{
    ptr = new something<int, true>(); // specialisation used
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM