gpt4 book ai didi

c++ - 模板偏特化

转载 作者:太空狗 更新时间:2023-10-29 19:44:42 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com