2011-04-17 32 views
2

可能容易解决,但它很难找到一个解决这个模板特殊化:必须有一整套的参数

是否可以(部分)专门用于一整套的类型? 在示例中,“Foo”应仅部分专用于(T,int)和(T,double),只有一个模板定义。

我可以做的是为(T,int)定义一个专门化。见下文。但是,它应该是(T,int)(T,double)只有一个函数定义(无代码加倍)。

template <typename T,typename T2> 
struct Foo 
{ 
    static inline void apply(T a, T2 b) 
    { 
    cout << "we are in the generic template definition" << endl; 
    } 
}; 

// partial (T,*) 
template <typename T> 
struct Foo<T, int >  // here something needed like T2=(int, double) 
{ 
    static inline void apply(T a, T2 b) 
    { 
    cout << "we are in the partial specialisation for (T,int)" << endl; 
    } 
}; 

任何想法如何用(T,int)和(T,double)部分专门化一个模板定义?

+1

编译器怎么可能知道该怎么做?它如何知道你想要打印''部分双精度''等等? – 2011-04-17 16:44:48

+0

输出仅用于了解使用哪个函数定义。 – ritter 2011-04-17 17:04:39

+0

哦,我现在明白了。 – 2011-04-17 17:06:03

回答

0

如果我理解正确的问题,那么你可以写一个基类模板,并从中获得,如下图所示:

template <typename T, typename U> 
struct Foo_Base 
{ 
    static inline void apply(T a) 
    { 
    cout << "we are in the partial specialisation Foo_Base(T)" << endl; 
    } 
}; 

template <typename T> 
struct Foo<T, int> : Foo_Base<T, int> {}; 

template <typename T> 
struct Foo<T, double> : Foo_Base<T, double> {}; 

虽然它不是一个模板定义(如你要求的),但你可以避免代码重复。

演示:http://www.ideone.com/s4anA

+0

谢谢你的回答。不幸的是,您使用了原始问题中应用的情况,这并不是这种意图。需要“两种”类型作为功能参数。对不起,我没有具体说明。 – ritter 2011-04-17 17:43:29

+0

@Frank:让我编辑答案吧! – Nawaz 2011-04-17 17:46:50

+0

@Frank:现在看我的答案。现在'Foo_Base'需要两个类型参数,因此我从它派生出来的时候传递它们 – Nawaz 2011-04-17 17:48:03

0

我相信你可以做到这一点使用Boost的enable_if启用你想要的类型局部特殊化。 3.1节展示了如何并给出这个例子:

template <class T, class Enable = void> 
class A { ... }; 

template <class T> 
class A<T, typename enable_if<is_integral<T> >::type> { ... }; 
相关问题