定义并调用 C++专用模板的功能
我目前正在深入学习C++,我遇到了一些已经困扰了几个小时的东西。 为什么当我创建一个模板然后对其进行专门化时,我无法为专门版本调用或定义该函数?编译器会抱怨,我已经在 Google 上搜索了可能的提示:我做错了什么,但无济于事。我非常确定我忽略了一些非常简单的事情:
template <typename T>
class C { };
//specialization to type char
template <>
class C <char>
{
public:
void echo();
};
//compiler complains here
template <>
void C <char> :: echo()
{
cout << "HERE" << endl;
}
错误:模板 ID 'echo<>' 'void C::echo()' 不匹配 任何模板声明
演示。
I am currently learning C++ in-depth, and I have come across something that has stumped for a couple hours now. Why is it when I make a template and then specialize it, that I can't call or define that function for the specialized version? The compiler complains, and I have scoured Google for a possible hint as to what I am doing wrong, but to no avail. I am very sure it is something very simple that I am overlooking:
template <typename T>
class C { };
//specialization to type char
template <>
class C <char>
{
public:
void echo();
};
//compiler complains here
template <>
void C <char> :: echo()
{
cout << "HERE" << endl;
}
error: template-id ‘echo<>’ for ‘void C::echo()’ does not match
any template declaration
Demo.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Ps 当您指的是
'\n'
时,切勿说endl
。 什么是 C++ iostream endl 惨败?P.s. Never say
endl
when you mean'\n'
. What is the C++ iostream endl fiasco?Robᵩ 的回答解决了这个问题。最好了解更多原因。
来自显式(完整)模板专业化:
Robᵩ's answer fixes the issue. It will be good to know more about the reason.
From Explicit (full) template specialization: