模板部分专业化 [英] Template partial specialization

查看:111
本文介绍了模板部分专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道根据什么规则下面的代码不编译?

Would any one knows according to what rules code below doesn't compile?

template <class T>
struct B
{
    typedef T type;
};

template<class T>
struct X
{
};
template<class T>
struct X<B<T>::type*>//HERE I'M PARTIALLY SPECIALIZING (WELL, TRYING TO...)
{
};

请参阅代码中的注释。

推荐答案

你认为这将如何工作?编译器会查看是否有类T有某个typedef类型到你的类?

How do you think that will work? The compiler will look to see if there is a class T somewhere that has a typedef "type" to your class?

它不会。即使它是一个指针。

It just won't. Even though it's a pointer.

请记住,大概你的B模板可能是专门的地方,所以类型不总是T *,但它不能推论与反向工程。

Remember that presumably your B template is presumably specialised in places so that type is not always T*, but it can't deduce it with reverse engineering.

对于那些不完全理解我的答案,你要求编译器做的是找到一个类U,使得B :: type是类传入作为参数。

For those who did not understand my answer fully, what you are asking the compiler to do is find a class U such that B::type is the class you pass in as a parameter.

class Foo;
class Bar;

template<> struct B<Foo>
{
  typedef int type;
};

template<> struct B<Bar>
{
  typedef int type;
};

X<int*> // ambiguous, T is Foo or Bar?

很难准确知道你为什么要做你自己。您可以对所有指针进行部分专门化,然后对特定指针进行总体专门化,这可以根据另一个模板实现。

It is difficult to know exactly why you are trying to do what you are. You can do a partial specialization on all pointers and then a total specialization on specific pointers, which could be implement in terms of another template.

这篇关于模板部分专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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