2014-04-01 133 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