【发布时间】:2016-08-24 14:11:04
【问题描述】:
我的编译器不支持if 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有一个对模板无效的分支,并且仍然能够为该模板实例化。 -
你在说什么
if constexpr? C++11 中没有这样的东西... -
@rubenvb 如果 constexpr 将在 C++17 中使用
-
@Eugene 问题是在发表评论时仍标记为 c++11。
-
专业化,不要使用
if。
标签: c++ templates if-statement constexpr c++17