【发布时间】:2009-11-25 14:45:10
【问题描述】:
我想专门化一个具有以下功能的类模板:
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++,但为什么呢?有没有办法优雅地实现这种模式?
【问题讨论】:
-
但是请注意,返回 T:
static int Foo() { return sizeof(T); }的大小不需要任何特化。我想知道这种模式是否对你真正的问题没有帮助。
标签: c++ templates specialization