【发布时间】:2015-08-11 01:13:05
【问题描述】:
我正在尝试了解 C++ 中的模板专业化。我已阅读其他论坛,但无法使其在实践中发挥作用。我正在尝试通过一个非常简单的示例来学习,我将对此进行解释。
我想要实现的目标:我希望 foo 根据类型表现出不同的行为。下面的代码不起作用,但我已经评论了我想看到的行为。有人可以填写我评论的行。 如果有什么不清楚的地方请告诉我。
#include <iostream>
#include <string>
template <typename T>
class my_template
{
public:
foo() {return 0} // default behavior if there does not exist foo() function for the specified type
};
template <>
class my_template<int>
{
public:
// implement foo function: should return -1 if the type = int
};
template <>
class my_template<long>
{
public:
// implement foo function: should return 100 if the type = long
};
int main()
{
my_template<int> x;
my_template<long> y;
my_template<double> z;
std::cout << x.foo() << "\n"; // print -1
std::cout << y.foo() << "\n"; // print 100
std::cout << z.foo() << "\n"; // print 0
return 0;
}
【问题讨论】:
-
@Jarod42 - 抱歉,我不知道有什么区别。我将更新标题并进行少量编辑。不过我的问题应该还是很清楚的。
-
polymorphim 是拼写错误...缺少一个“s”。
-
fooinsidemy_template也不应该像你拥有的那样编译(没有返回类型) -
@Jarod42 - 模板特化是否被认为是多态行为?
标签: c++ generics polymorphism