gpt4 book ai didi

c++ - 模板参数中的类指针 - 这有什么用?

转载 作者:行者123 更新时间:2023-11-28 07:44:19 31 4
gpt4 key购买 nike

template <typename T> struct s
{

};

template <> struct s<MyClass *>
{

};

... in main function
struct s<MyClass*> obj;

上面的代码可以编译,但我真的看不出完全特化可以做什么

template <> struct s<MyClass *>
{

};

我不能像这样添加一个指针变量(既不是常量也不是静态的)

template <> struct s<MyClass *obj > // ERROR
{

};

那么上面的特化有什么意义呢?我不能使用 MyClass *“匿名”指针

最佳答案

I can't add a pointer variable (neither constant or static) like

template <> struct s<MyClass *obj > // ERROR
[...]

您可能对这里有误解。如果您关心的用例是要提供指向用户定义类实例的指针作为非类型模板参数,那么这与模板特化 无关。

特别是,根据 C 的第 14.3.2/1 段,考虑到您可以指定一个指向类的全局实例的指针作为模板参数++11标准:

A template-argument for a non-type, non-template template-parameter shall be one of:

— for a non-type template-parameter of integral or enumeration type, a converted constant expression (5.19) of the type of the template-parameter; or

— the name of a non-type template-parameter; or

— a constant expression (5.19) that designates the address of an object with static storage duration and external or internal linkage or a function with external or internal linkage, including function templates and function template-ids but excluding non-static class members, expressed (ignoring parentheses) as & id-expression, except that the & may be omitted if the name refers to a function or array and shall be omitted if the corresponding template-parameter is a reference; or

[...]

这可能是您想要实现的目标:

struct MyClass { };

MyClass c;

template<MyClass* p>
// ^^^^^^^^ Non-type template argument
struct s
{
// Possibly work with p
};

int main()
{
s<&c> obj;
}

关于模板特化:

关于您编写​​的代码,您的主要模板处理任何类型:

template <typename T> struct s
{
// Definition...
};

并且这种显式特化(这是技术名称,不是“完全”特化)允许您在用于实例化主模板的参数是MyClass*:

template <> struct s<MyClass *>
{
// Definition when the template argument is `MyClass*`
};

例如,您可以这样做:

struct MyClass { };

template <typename T> struct s
{
void print() { cout << "Primary template!" << endl; }
};

template <> struct s<MyClass *>
{
void print() { cout << "Specialization for MyClass*!" << endl; }
};

int main()
{
s<int> obj;
obj.print(); // Will print "Primary template!"

s<MyClass*> obj;
obj.print(); // Will print "Specialization for MyClass*!"
}

另请注意,专用模板的定义可能与主模板的定义完全不同:

template <typename T> struct s
{
void print() { cout << "Primary template!" << endl; }
};

template <> struct s<MyClass *>
{
void greet() { cout << "Specialization for MyClass*!" << endl; }
};

int main()
{
s<int> obj;
obj.print(); // Will print "Primary template!"

s<MyClass*> obj;
obj.greet(); // Will print "Specialization for MyClass*!"
obj.print(); // ERROR! s<MyClass*> has no `print()` member function
}

当然,这只是类模板特化工作原理的一个例子。以我的方式区分主要模板和专用模板的定义没有任何用处。

但是,存在许多现实世界的用例。例如,可以针对某些特定类型以完全不同的方式优化和重写通用算法。

模板特化的另一个重要应用是定义特征,您可能需要阅读相关内容。

关于c++ - 模板参数中的类指针 - 这有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15175434/

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