我的編譯器不支持if constexpr
,但我被它的好處所吸引。
我必須擁有它 - 即使它可能是假的。模仿「如果constexpr」的行爲,不可能?
此代碼是我試圖模仿if constexpr
的行爲。
目的是使線(###)僅出現在1個功能: -
#include <iostream>
using namespace std;
template<bool Flag,typename F> constexpr typename std::enable_if<!Flag, void>::type iter_(F f,int i1){
f(i1); //No! The compiler still tried to compile even Flag=true
}
template<bool Flag,typename F> constexpr typename std::enable_if<Flag, void>::type iter_(F f,int i1){ }
template<bool Flag,typename F> constexpr typename std::enable_if<Flag, void>::type iter_(F f,int i1,int i2){
f(i1,i2); //No! The compiler still tried to compile even Flag=false
}
template<bool Flag,typename F> constexpr typename std::enable_if<!Flag, void>::type iter_(F f,int i1,int i2){}
template<bool Flag,typename F> constexpr void fff( F f ){
for(int n=0;n<5;n++){//fake loop, the real situation is very complex
//### some horror code appeared here, but omitted
if(Flag){//attempt to mimic "if constexpr"
iter_<true>(f,1,2);
}else{
iter_<false>(f,3);
}
}
}
這是它的用法: -
template<typename F> constexpr void fff1( F f ){fff<false>(f);} //usage
template<typename F> constexpr void fff2( F f ){fff<true>(f);} //usage
int main() {
// your code goes here
auto f1=[&](int a){
cout<<a<<" ";
};
auto f2=[&](int a,int b){
cout<<a<<" "<<b<<endl;
};
fff1(f1);
fff2(f2);
return 0;
}
我得到了編譯錯誤:
prog.cpp: In instantiation of 'constexpr typename std::enable_if<Flag, void>::type iter_(F, int, int) [with bool Flag = true; F = main()::<lambda(int)>; typename std::enable_if<Flag, void>::type = void]':
prog.cpp:16:18: required from 'constexpr void fff(F) [with bool Flag = false; F = main()::<lambda(int)>]'
prog.cpp:22:61: required from 'constexpr void fff1(F) [with F = main()::<lambda(int)>]'
prog.cpp:33:9: required from here
prog.cpp:9:3: error: no match for call to '(main()::<lambda(int)>) (int&, int&)'
f(i1,i2);
^
prog.cpp:9:3: note: candidate: void (*)(int) <conversion>
prog.cpp:9:3: note: candidate expects 2 arguments, 3 provided
從錯誤,我很清楚,即使函數有std :: enable_if [生效 FALSE],
編譯器仍編譯該函數內部的代碼。 - 這很糟糕。
哪些部件需要編輯?
...或者有沒有其他的選擇?
......還是根本不可能模仿if constexpr
(這就是爲什麼最終被引入的原因)?
是的,模板中的所有代碼都必須是有效的。所以不,沒有辦法讓'if'具有對模板無效的分支,並且仍然能夠爲該模板實例化。 – bolov
你在說什麼,如果constexpr?在C++ 11中沒有這樣的東西...... – rubenvb
@rubenvb如果constexpr將在C++中17 – Eugene