繁体   English   中英

具有模板化类型的模板专业化

[英]Template specialization with a templatized type

我想使用以下函数专门化一个类模板:

template <typename T>
class Foo
{
public:
    static int bar();
};

该函数没有参数,应根据Foo的类型返回结果。 (在这个玩具示例中,我们返回该类型的字节数,但在实际应用程序中我们要返回一些元数据对象。)专门化适用于完全指定的类型:

// specialization 1: works
template <>
int Foo<int>::bar() { return 4; }

// specialization 2: works
template <>
int Foo<double>::bar() { return 8; }

// specialization 3: works
typedef pair<int, int> IntPair;
template <>
int Foo<IntPair>::bar() { return 2 * Foo<int>::bar(); }

但是,我想将此概括为依赖于(其他)模板参数本身的类型。 添加以下特化会产生编译时错误(VS2005):

// specialization 4: ERROR!
template <>
template <typename U, typename V>
int Foo<std::pair<U, V> >::bar() { return Foo<U>::bar() + Foo<V>::bar(); }

我假设这不是合法的C ++,但为什么呢? 有没有办法优雅地实现这种类型的模式?

Partitial specialization仅对类而不是函数有效。

解决方法:

template <typename U, typename V>
class Foo<std::pair<U, V> > { 
public:
 static int bar() { return Foo<U>::bar() + Foo<V>::bar(); }
};

如果您不想完全专门化类,请使用辅助结构

template<class T>
struct aux {
  static int bar();
};

template <>int aux <int>::bar() { return 4; }
template <>int aux <double>::bar() { return 8; }

template <typename U, typename V>
struct aux <std::pair<U, V> > { 
  static int bar() { return Foo<U>::bar() + Foo<V>::bar(); }
};

template<class T>
class Foo : aux<T> {
  // ... 
};

它在C ++中是完全合法的,它是部分模板专业化。
删除template <>如果它还不存在,请添加显式类模板特化,它应该在VS2005上编译(但不能在VC6中编译)

// explicit class template specialization
template <typename U, typename V>
class Foo<std::pair<U, V> >
{
public:
    static int bar();
};

template <typename U, typename V>
int Foo<std::pair<U, V> >::bar() { return Foo<U>::bar() + Foo<V>::bar(); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM