我正在爲源編譯器編寫某種源代碼,並且此刻我產生了一組if
語句,這些語句允許我實例化正確的模板對象。這些對象需要bool...
,所以有些可能需要合理的一個,其他許多。它看起來像:來自動態值的可變參數模板類型
if(unknow_at_compilation==1){
if(unknown2 == 3){
My_obj<true> A;
My_obj<true, false> B;
/*do something X*/
}else{
My_obj<true> A;
My_obj<false, false> B;
/*do same thing X*/
}else{
if(unknown2 == 3){
My_obj<false> A;
My_obj<true, true> B;
/*do same thing X*/
}else{
My_obj<false> A;
My_obj<false, true> B;
/*do same thing X*/
}
}
但有更多的條件和對象。我不能使用多態性和指針,因爲性能是我應用程序中的關鍵點,並且對象A
和B
被大量使用。
而不是如果if
if
我想使用metaprogrammation該複雜的繼承。然而,我面臨一些嚴重的困難...... 在我這一代,我知道我需要的對象的數量以及需要多少「布爾」。
第一步是封裝在模板結構中的「有所作爲」部分以套布爾:
template<bool... val>
struct bool_set{};
template<typename T1, typename T2>
struct struct_do_something;
template<bool... b1, bool... b2>
struct struct_do_something<bool_set<b1...>, bool_set<b2...>>
{
static void do_something(){
My_obj<b1...> i;
My_obj<b2...> j;
/*Do something*/
}
};
這件作品,我可以把它像(例如):struct_do_something<bool_set<true, true>, bool_set<false, false>>::do_something();
然後,我寫了一個使用條件生成單個bool_set
的結構。
template<bool... static_vals> //bool values of the currently created bool_set
struct bool_set_generator{
template<typename... Bool>
static void select(bool v1, Bool... dynamic_vals) //Conditions in parameters
{
if(v1)
return bool_set_generator<static_vals..., true>::select(dynamic_vals...);
else
return bool_set_generator<static_vals..., false>::select(dynamic_vals...);
}
static void select(){
/*I have a bool_set here -> I can "do something"*/
struct_do_something<bool_set<static_vals...>>::do_something();
}
};
很顯然,這不是結束:我可以生成一個bool_set
所以我的想法是存儲bool_set
已創建+目前這樣創建的:
template <typename... Created, bool... static_val>
但是編譯器(G ++ 5.4與-std = C++ 11)告訴我parameter pack ‘Created’ must be at the end of the template parameter list
和我與其他開關,它說相同...
有人有一個想法? 最後,我想打電話給我的功能一樣,(或同等學歷):(?函數)
generate_the_do_something<>::call({cond1, cond2}, {cond3, cond4, cond5});
每個初始化列表是bool_set
,這generate_the_do_something
是一種結構,將創建bool_set
和與他們聯繫do_something()
。
非常感謝!我已經成功修改它以將參數添加到函數「func」:) 我終於不需要'std :: enable_if',但它是瞭解它如何工作以及何時使用它的好例子,再次感謝:) – Viridya