泛型编程中带有关键字模板的规范
Specification with keyword template in the generic programming
#include <iostream>
namespace oo{
class A{
public:
template<typename T>
static T get_value(){return static_cast<T>(55);}
};
template <typename T=A>
class B{
public:
static double f(){return T::get_value<double>();}
};
}
int main(int argc, char *argv[])
{
using std::cout;
using std::endl;
cout << oo::B<oo::A>::f() << endl;
return 0;
}
考虑到这里的例子,它编译时出现错误"不允许类型名称",该错误引用"double"和"get_value(("中的参数。
有人通过重写函数 f(( 来纠正这个错误,如下所示:
static double f(){return T::template get_value<double>(); }
然而,我不太明白这里"模板"的使用。谁能向我解释一下,请?
提前感谢您的评论。
原因是编译器如何解释那行,当你使用模板时,语法有多个可能的解释,看看下面:
static double f()
{
return T::get_value < double > ();
}
在您的函数中,您现在传递给 B 类的 T 参数如何具有名为 get_value 的函数或名为 get_value 的数据成员?如果情况是第二种,则在该成员和双精度之间,然后在双精度和 (( 之间使用运算符 lees-than。那么编译器的第一个假设是这些选项,如果你告诉他这是一个带有模板的函数(为了正确解释"<"(,你需要把关键字模板
这就是
运行时发生的事情。
namespace oo{
class A{
public:
// template<typename T> // T replaced with <double> type.
static double get_value(){return static_cast<double>(55);}
};
//template <typename T=A> // T replaced with <oo::A> type.
class B{
public:
static double f(){return oo::A::get_value/*<double>*/();}
};
}
int main(int argc, char *argv[])
{
using std::cout;
using std::endl;
cout << oo::B::f() << endl;
return 0;
}
这一行: 静态双精度 f(({return T::get_value((;}是正确的,通常编译时没有任何错误(取决于您使用的女巫编译器(,因为模板声明对下一个范围有效。
template <class T>
class foo
{
//T will be valid in this scope.
};
实现模板类/函数不是这种情况,在想要防止使用多个重载的情况下,您通常希望这样做。
相关文章:
- 使用泛型编程的基本数据结构
- 在泛型编程中使用新的放置
- 在泛型编程中选择类型参数
- 在泛型编程C++重载增量运算符
- 处理C++泛型编程中的空分配
- 有关C++泛型编程的错误
- 在泛型编程中,需要在派生类中重新声明基类成员函数
- 将泛型编程与多态性混合在一起
- C++泛型编程 CRTP 基类继承自派生类型提供的类
- 泛型编程中带有关键字模板的规范
- 为什么泛型编程设计更喜欢自由函数而不是成员函数
- c++如何在泛型编程中声明自定义数组
- C++函数式和泛型编程[使用MySQL连接器示例]
- 继承和虚函数与泛型编程
- 虚函数与泛型编程
- 只使用<泛型编程中的比较
- c++泛型编程与模板和nullptr
- c++中的泛型编程和类中的类型定义
- 如何在c++中使用泛型编程来代替多态性
- 概念与复制构造函数冲突的泛型编程