模板函数默认参数
Template function default parameter
//template.h using MSVC++ 2010
#pragma once
#include <iostream>
using std::ostream;
template <typename T, typename U> class Pair {
private:
T first;
U second;
public:
// Pair() ;
Pair ( T x = T() , U y = U() ) ;
template<typename T, typename U>
friend ostream& operator<< ( ostream& thisPair, Pair<T, U>& otherPair );
};
template <typename T, typename U>
Pair<T, U>::Pair ( T x , U y ) : first ( T ( x ) ), second ( U ( y ) )
{cout << x << y;}
template <typename T, typename U>
ostream& operator<< ( ostream& os, Pair<T, U>& otherPair )
{
os << "First: " << otherPair.first
<< " "<< "Second: " << otherPair.second << endl;
return os;
}
//template.cpp
int main()
{
int a = 5, b = 6;
Pair<int,int> pair4();
Pair<int, int> pair1 ( a, b );
cout<<pair4;
cout<<pair1;
return 0;
}
如何使构造函数或成员函数取默认值?上面的代码在使用 cout 语句时为 pair4 提供链接器错误。代码在 cout<<pair4(( 时完美运行;被评论。我正在尝试使用模板类中的单个默认构造函数来模拟采用 0,1 或 2 参数的构造函数。
除了其他错误,如阴影模板参数(MSVC++ 错误地忽略了这些参数(,问题就在这里:
Pair<int,int> pair4();
这将声明一个函数而不是一个变量。这是因为它在语法上可以是两者,并且C++标准选择最令人烦恼的解析:编译器可以解释为声明的任何内容都将被解释为声明。然后,链接器错误是您尝试打印到从未定义(没有地址(的函数cout
地址。
旁注:在GCC和Clang中,您实际上可以链接它,因为地址会立即转换为bool
以进行operator <<
(没有运算符用于打印指向ostream
的函数指针,并且bool
是唯一可用的隐式转换(,这将始终导致true
(声明函数的地址永远无法nullptr
(,因此地址本身被优化掉。
修复非常简单:
Pair<int,int> pair4;
相关文章:
- 使函数参数默认为周围范围
- 如何将值传递给其参数(默认参数)
- 当“std::make_index_sequence”和“std::index_sequence”用于模板参数默认类型时
- C ,构造器中允许的参考参数默认值
- 哪些规则控制参数默认赋值?
- 错误:上一个规范后给出的参数默认参数
- 是否可以设计一个包含模板参数默认值的类
- 构造函数中参数C++默认值
- 如何设置依赖于其他参数的参数默认值
- C++模板参数默认函数实现
- QInput对话框参数默认值
- g++4.8.2上列表方法参数默认初始化时出错
- 在函数定义中指定参数默认值会导致错误 C2143:语法错误:'='之前缺少')'
- 函数模板:将第一个模板参数默认为第二个
- 模板模板参数默认可以引用其他模板类型的参数
- 参数默认为先例参数的值
- 如何修改一个类,使它只有一个成员函数,所有参数默认
- 内置类型的模板参数默认值
- 是否可以使用构造函数或对象作为其他类方法的参数默认值?
- 模板参数默认为更高版本