双模板<>语句

Double template<> statements

本文关键字:gt 语句 lt      更新时间:2023-10-16

有这样的函数定义:

template<>
template<>
void object::test<1>()
{
}

有双模板<>是什么意思?

编辑:

我提取的代码对这个例子有效:

#include <iostream>
template <class U>
class A {
    template <int n>
    void test() {
    }
};
template <class T>
class B {
public:
    typedef A<T> object;
};
typedef B<int>::object object;
template<>
template<>
void object::test < 1 > () {
}
int main() {
    return 0;
} 

此代码在g++下编译。

来源:TUT测试框架

例如

template<class T = int> // Default T is int
class object<T> {
   template<int R> void test ();
};
代码:

template<> // T is fixed
template<> // R is fixed
void object<>::test<1>() // T is default int, R is 1
{
}

等价于:

template<> // T is fixed
template<> // R is fixed
void object<int>::test<1>() // T is int, R is 1
{ 
} 

这是类模板成员函数模板的模板专门化(我没记错吧?),带有模板的默认形参。看这个:

template<typename T = int>
struct X {
  template<typename U>
  void foo(U u);
};
template<>
template<>
void X::foo(float f) { }

这为X的模板参数为intX<int>::foo的实参为float的情况引入了专门化。这种情况与您的情况略有不同,我们不必在成员函数的名称之后显式地提供模板参数,因为它可以推断出来。你的函数有一个非类型模板参数,不能推导,因此必须提供。

最让我困惑的是默认模板参数,我不确定使用跳过它是否是一个好的实践。我会为每个专门化提供它,以避免混淆。

这看起来像是类模板内函数模板的专门化。例如,考虑下面的类模板定义:

template <int m=1>
class object
{
public:
  template <int n>
  void test();
};
// This differs from your example, by the addition of `<>` after `object`, but it's as
// close as I can come to valid code true to your example
template<> 
template<> 
void object<>::test<1>() 
{ 
}