2012-11-22 47 views
5

是否已經實現,因爲這並不編譯:(使用gcc 4.7.2)可變參數模板專業化C++ 11

template <typename... Ts> 
struct Foo { 
    int foo() { 
     return 0; 
    } 
}; 

template <> 
struct Foo<int x, int y> { 
    int foo() { 
     return x * y; 
    } 
}; 

int main() 
{ 
    Foo<2, 3> x; 
    cout << x.foo() << endl; //should print 6 
} 
+0

如果它不能編譯,什麼是編譯器的抱怨? –

+0

可變參數模板早已在gcc中實現。如果你想檢查功能支持:http://gcc.gnu.org/projects/cxx0x.html –

回答

10

你正在犯了一些錯誤。主模板需要類型,而不是 積分常量。您還嘗試使用 整型常量實例化模板,但是您的部分特化使用類型。

這是接近:

#include <iostream> 

template <int... Ts> 
struct Foo { 
    int foo() { 
     return 0; 
    } 
}; 

template <> 
struct Foo<3, 2> { 
    const int x = 3; 
    const int y = 2; 

    int foo() { 
    return x * y; 
    } 
}; 

int main() 
{ 
    Foo<2, 3> x; 
    std::cout << x.foo() << std::endl; //should print 6 
} 

但是,這是不是真的我們想要的,對不對?而且它也很笨拙。

#include <iostream> 

template<typename Acc, typename... Rest> 
struct accum_help; // primary 

template<typename Acc, typename F, typename... Rest> 
struct accum_help<Acc, F, Rest...> { 
    typedef typename accum_help< 
    std::integral_constant<typename Acc::value_type, 
          Acc::value * F::value>, Rest... 
    >::type type; 
}; 

template<typename Acc> 
struct accum_help<Acc> { 
    typedef Acc type; 
}; 

// peek into the first argument to avoid summing empty sequences and 
// get the right type 
template<typename X, typename... Integrals> 
struct accum { 
    typedef typename accum_help< 
    std::integral_constant<typename X::value_type, 1>, X, Integrals... 
    >::type type; 
}; 

int main() 
{ 

    std::cout << accum< std::integral_constant<int, 2>, std::integral_constant<int, 3> >::type::value << std::endl; //should print 6 
} 

一個簡單的變體只處理INT:

template <int...> 
struct accum2_help; 

template <int Acc, int X, int... Rest> 
struct accum2_help<Acc, X, Rest...> { 
    static const int value = accum2_help< Acc * X, Rest...>::value; 
}; 

template <int Acc> 
struct accum2_help<Acc> { 
    static const int value = Acc; 
}; 

// again don't accept empty packs 
template <int T, int... Ts> 
struct accum2 { 
    static const int value = accum2_help<1, T, Ts...>::value; 
}; 
+0

所以如何做到這一點:1.聲明''版本的'Foo'並用常量' <2, 3>'? – Cartesius00

+0

'Foo <2, 3> x'?它應該不是'Foo <3, 2> x'? – Nawaz

+0

@Martin如果你想能夠使用'Foo'作爲'Foo <2, 3>',那麼它看起來像你想要的主要模板是'template struct Foo;'。 –