5
默認模板參數可用於模擬模板聲明中複雜類型表達式的別名。例如:是否可以模擬部分專業化中的默認模板參數?
template <typename X,
typename Y = do_something_with<X>::type,
typename Z = some_other_thing_using<X, Y>::type
struct foo { ... X, Y, Z ... };
然而,部分特例不能有默認模板參數([C++11: 14.5.5/8]
),所以這招不起作用。你可能會問自己,爲什麼在身體中的typedef不起作用,並且答案是別名需要位於班級體的範圍之內,以便進行有條件的啓用;例如:
template <typename T, typename Enable = void>
struct bar;
// Wishful thinking:
template <typename X,
typename Y = do_something_with<X>::type,
typename Z = some_other_thing_using<X, Y>::type>
struct bar <std::vector<X>,
typename enable_if<
some_condition<X, Y, Z>
>::type>
{ ... };
我周圍的工作方式是使用輔助類型:
template <typename X>
struct bar_enabled {
typedef typename do_something_with<X>::type Y;
typedef typename some_other_thing_using<X, Y>::type Z;
static const bool value = some_condition<X, Y, Z>::value;
};
template <typename X>
struct bar <std::vector<X>,
typename enable_if_c<
bar_enabled<X>::value
>::type>
{ ... };
但由於種種原因(其中包括想避免一個單獨的類型,複雜化,我什麼做),我希望有更好的解決方案。有任何想法嗎?
默認參數沒有任何模擬。他們提供默認值。 – 2012-03-15 21:41:28
爲了記錄,「專業化模板參數列表不應包含默認模板參數值」[C++ 11:14.5.5/8]' – 2012-03-15 21:42:27
@LightnessRacesinOrbit,你的意思是指出這個問題沒有'在C++ 11中改變了,還是其他的東西? – ajg 2012-03-15 21:54:00