kmh*_*ann 9 c++ templates specialization
我想使用以下函数专门化一个类模板:
template <typename T>
class Foo
{
public:
static int bar();
};
Run Code Online (Sandbox Code Playgroud)
该函数没有参数,应根据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(); }
Run Code Online (Sandbox Code Playgroud)
但是,我想将此概括为依赖于(其他)模板参数本身的类型.添加以下特化会产生编译时错误(VS2005):
// specialization 4: ERROR!
template <>
template <typename U, typename V>
int Foo<std::pair<U, V> >::bar() { return Foo<U>::bar() + Foo<V>::bar(); }
Run Code Online (Sandbox Code Playgroud)
我假设这不是合法的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(); }
};
Run Code Online (Sandbox Code Playgroud)
如果您不想完全专门化类,请使用辅助结构
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> {
// ...
};
Run Code Online (Sandbox Code Playgroud)
它在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(); }
Run Code Online (Sandbox Code Playgroud)