C++ 模板参数中的类指针-这对什么有用? 模板结构 { }; 模板结构 { }; ... 主要功能 结构对象;
上面的代码可以编译,但我真的看不出完全专门化可以做什么C++ 模板参数中的类指针-这对什么有用? 模板结构 { }; 模板结构 { }; ... 主要功能 结构对象;,c++,templates,C++,Templates,上面的代码可以编译,但我真的看不出完全专门化可以做什么 template <typename T> struct s { }; template <> struct s<MyClass *> { }; ... in main function struct s<MyClass*> obj; 模板结构 { }; 我不能像这样添加指针变量(常量或静态) 模板结构//错误 { }; 那么上面的专业化有什么意义呢?我不能使用MyClass*“
template <typename T> struct s
{
};
template <> struct s<MyClass *>
{
};
... in main function
struct s<MyClass*> obj;
模板结构
{
};
我不能像这样添加指针变量(常量或静态)
模板结构//错误
{
};
那么上面的专业化有什么意义呢?我不能使用MyClass*“anonymous”指针当您实例化模板(隐式或显式)时,您提供了一个类型:
template <> struct s<MyClass *obj > // ERROR
{
};
然后对象s1
具有类型int
的名为x
的成员,s2
具有类型float
的名为x
的成员,s3
具有类型MyClass
的名为x
的成员
您所给出的显式专门化的要点是,当传递给模板参数的类型是MyClass*
时,提供不同的s
实现,如下所示:
template <typename T> struct s {
T x;
};
s4;
例如,考虑一个显式的专业化,它看起来像:
s<MyClass*> s4;
模板结构
{
int x;
};
对象s4
将有一个名为x
的int
类型的成员,尽管其模板参数为MyClass*
。我们特别说过“当模板参数类型为MyClass*
时,结构将有一个成员intx
”
此s4
对象将使用s
的显式专门化,而不是更通用的版本。当您知道模板参数是MyClass*
时,也许可以更有效地实现类
我不能像这样添加指针变量(常量或静态)
例如,您可以这样做:
template <> struct s<MyClass *>
{
// Definition when the template argument is `MyClass*`
};
struct MyClass{};
模板结构
{
void print(){如果您需要为MyClass*
定制行为,那么它可能会很有用吗?基于这一点和您之前的问题:您可能误解了模板的整个概念。它们是编译时构造。
s<MyClass*> s4;
template <> struct s<MyClass*>
{
int x;
};
template <> struct s<MyClass *obj > // ERROR
[...]
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...
};
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
}