2014-04-01 134 views
1

假设我有一个类模板如何在函数模板中声明模板专门化?

template<int I, int J> class bar { /* ... */ }; 

,并希望与结合的第二个模板参数(固定)使用下面的模板的模板

template<template<int> class C> 
struct foo { void func(some_type arg); }; 

C等于bar。实现这一目标的方法之一是

template<int J, template<int, int> class B> 
struct use_foo_helper { 
    template<int I> using BJ = B<I,J>; 
    static void func(some_type arg) { foo<BJ>::func(arg); } 
}; 
template<int J> 
void foo_bar(some_type arg) { use_foo_helper<J,bar>::func(arg); } 

但是,创建一个辅助类(use_foo_helper)只是为了这个目的是相当不方便。我宁愿想只要定义函数模板foo_bar,但没有成功

template<int J> 
void foo_bar(some_type arg) 
{ 
    // template<int I> using barJ = bar<I,J>; // this appears to be illegal 
    // for<barJ>::func(arg); 
    foo<???>::func(arg);      // what shall I put in place of ??? 
}; 

Q有没有办法避免的辅助类? Q有没有更好的设计模式达到相同?

回答

1

您可以通过以下方式做到这一点:使用

template <int I, int J> 
class bar{}; 

template <template<int> class C> 
struct foo 
{ 
    static 
    void func(some_type arg){} 
}; 

template <int J> 
class foo_bar 
{ 
    template <int I> 
    using barJ = bar<I, J>; 

public: 

    static 
    void call(some_type arg) 
    { 
     foo<barJ>::func(arg); 
    } 
}; 

例子:foo_bar</*...*/>::call(/*...*/);

但如果你只想解决您的类模板的一个参数,这是可以做到简单:

template <int J> 
struct barJ 
{ 
    template <int I> 
    using type = bar<I, J>; 
}; 

示例使用:foo<barJ</*...*/>::type>::func(/*...*/);

+0

您仍然使用辅助助手类'foo_bar'和'barJ'。那么你是说,那些无法避免?如果是这样,你能证明这一点吗? – Walter

+0

@Walter对不起,我不注意地阅读你的问题。是的,我认为你不能避免使用助手类。不,我不能证明这一点。但我知道你甚至不能将模板声明为本地类的成员(见14.5.2/2),所以... – Constructor