作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
有谁知道下面的代码根据什么规则不能编译?
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“类型”?
就是不会。尽管它是一个指针。
请记住,您的 B 模板可能专门用于某些地方,因此类型并不总是 T*,但它无法通过逆向工程推断出它。
对于那些没有完全理解我的回答的人,您要求编译器做的是找到一个类 U,使得 B::type 是您作为参数传入的类。
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?
很难确切知道您为什么要尝试做现在的事情。您可以对所有指针进行部分特化,然后对特定指针进行完全特化,这可以根据另一个模板来实现。
关于c++ - 模板偏特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5211205/
我是一名优秀的程序员,十分优秀!