模板函数默认参数

Template function default parameter

本文关键字:参数 默认 函数      更新时间:2023-10-16
//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;