[英]Strange class template specialization
I have a class template 我有一个课程模板
template <class T>
class A
{
};
and very strange specialization 而且非常奇怪的专业化
template <>
class A<class T*> : private A<void *>
{
};
Can anybody explain the meaning of this construction ? 任何人都可以解释这种结构的含义吗?
The obfuscation declares a class T and specialize the template for T* 混淆声明了一个类T并专门为T *模板
#include <iostream>
template <class T>
class A
{
public:
static void f() { std::cout << "Template" << '\n'; }
};
// Declare a class T and specialize the template for T*
template <>
class A<class T*> : private A<void *>
{
public:
static void f() { std::cout << "Specialization" << '\n'; }
};
class T {};
int main()
{
// Template
A<int*>::f();
// Specialization
A<T*>::f();
}
I think that the intended code would be: 我认为预期的代码是:
template <class T>
class A<T *> : public A<void*>
{
};
That is a partial specialization that will be used for any pointer type, instead of the generic one. 这是一个部分特化,将用于任何指针类型,而不是通用指针类型。 That is, any time
A
is instantiated using a pointer type, it will use this declearation instead of the generic one. 也就是说,任何时候使用指针类型实例化
A
,它将使用此declearation而不是泛型。
Naturally you need to instantiate, or otherwise spezialize the A<void*>
, before this declaration, or else you will have an infinite recursion: 当然,您需要在此声明之前实例化或以其他方式使
A<void*>
特殊化,否则您将获得无限递归:
template class A<void*>;
This is a somewhat common idiom to force the compiler to reuse code. 这是迫使编译器重用代码的一种常见习惯用法。 That is, you know that every instance of
A<T*>
is basically the same, as all pointers will behave identically under the hood. 也就是说,您知道
A<T*>
每个实例基本相同,因为所有指针在引擎盖下的行为都相同。 So you provide the full instantiation of A<void*>
and then any other A<T*>
inherits from it, doing the casts inline where needed. 因此,您提供
A<void*>
的完整实例化,然后任何其他A<T*>
继承自它,在需要的地方进行内联转换。
Since A<T*>
inherits from A<void*>
it does not need to provide the bulk of the class code in its instantiation. 由于
A<T*>
继承自A<void*>
因此不需要在其实例化中提供大量的类代码。 Smaller code will hopefully will yield better performance. 较小的代码有望产生更好的性能。
Full example ahead, untested: 未完整的示例:未经测试:
template <typename T>
class A
{
public:
A()
:m_data(0)
{}
void set(T x)
{ m_data = x; }
T get()
{ return m_data; }
//here there will be more complex operations
private:
T m_data;
//and a lot of data depending on T
};
template class A<void*>; //splicit instantiation
template <typename T>
class A<T*> : public A<void*>
{
private:
typedef A<void*> base_type;
public:
//only the public, and maybe protected, functions are needed
//but the implementation is one-line each
void set(T *x)
{ base_type::set(x); }
T *get()
{ return static_cast<T*>(base_type::get()); }
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.