如何定义另一个模板类的内部模板类的构造函数?

时间:2015-10-27 15:27:16

标签: c++ templates

我有另一个模板类的内部模板类:

test()

function dateChecker(re, dOrder, s) {
  var validity = {
    pass: false,
    testString: s
  }
  s.replace(re, function(full, date, seperator, time) {
    var y, m, d, h, min, s, p;
    date = date.split(seperator).map(Number);
    date[1] --;
    time = time ? time.split(':').map(Number) : [0, 0, 0];
    p = new Date(
      y = date[dOrder.y],
      m = date[dOrder.m],
      d = date[dOrder.d],
      h = time[0],
      min = time[1],
      s = time[2]);
    if (p.getDate() === d && 
        p.getMonth() === m && 
        p.getFullYear() === y && 
        p.getHours() === h && 
        p.getMinutes() === min && 
        p.getSeconds() === s)
      validity.pass = true;
    else
      validity.failReason = [p, "doesn't match", date, time].join(' ')
  });
  return validity
}

function dValidator(s) {
  return dateChecker(/^((?:\d\d([-\/])){2}\d{4})(?:\s+((?:\d\d:){2}\d\d))?$/, {
    d: 0,
    m: 1,
    y: 2
  }, s)
}

function test() {
  var failedTests = [],
    failData = ["33/09/2064", "31/2/1980"],
    sucessData = ["14-03-1904 04:35:17", "29/2/1980"];
  failData.map(dValidator).map(function(a, i) {
    return a.pass ? failedTests.push([a, i, 'expected to fail but it incorrectly passed']) : console.log('test passed ok', a, i)
  })
  sucessData.map(dValidator).map(function(a, i) {
    return a.pass ? console.log('test passed ok', a, i) : failedTests.push([a, i, 'expected to pass but it has incorrectly failed'])
  })
  if (failedTests.length) {
    console.log(failedTests);
    return 'fail'
  }
  return 'pass'
}

当我声明内部类构造函数时,我遇到了一些错误:

// hpp file
template< class T1 > class C1
{
   // ...
public:
   // ...
   C1();
   template< class T2 > C2
   {
      // ...
      C2();
   };
};

我也尝试过:

//cpp file
template<> C1< MyType >::C1()
{
   // ...
}

template<> template< class T2 > C1< MyType >::C2::C2() // error: invalid use of template-name ‘class C1<MyType>::C2’ without an argument list    
{
   // ...
}

类型不完整,但构造函数没有类型......

我有点卡在这里。如何申报?

2 个答案:

答案 0 :(得分:2)

执行以下操作:

template<typename T1>
template<typename T2>
C1<T1>::C2<T2>::C2()
{
}

答案 1 :(得分:1)

您无法通过定义内部模板类的方法来专门化外部类。如果你想专门化内部类和外部类,你可以:

template<>
template<> 
C1<MyType>::C2<char>::C2()
{
   // ...
}

LIVE

如果你想保持内部类的通用性,你应该首先专门化外部类:

template<> 
class C1<MyType>
{
   // ...
public:
   // ...
   C1();
   template< class T2 > class C2
   {
      public:
      // ...
      C2();
   };
};

然后定义C2的构造函数,

template<class T2> 
C1<MyType>::C2<T2>::C2()
{
   // ...
}

LIVE