考虑以下代码:
#include <iostream>
#include <type_traits>
template<typename T> class MyClass
{
public:
MyClass() : myVar{0} {;}
void testIf() {
if (isconst) {
myVar;
} else {
myVar = 3;
}
}
void testTernary() {
(isconst) ? (myVar) : (myVar = 3);
}
protected:
static const bool isconst = std::is_const<T>::value;
T myVar;
};
int main()
{
MyClass<double> x;
MyClass<const double> y;
x.testIf();
x.testTernary();
y.testIf(); // <- ERROR
y.testTernary(); // <- ERROR
return 0;
}
对于 x(非常量)没有问题.但是 y(const 数据类型)会导致错误,即使 if/else 中的条件在编译时已知.
For x (non-const) there is no problem. But y (const data type) cause an error even if the condition in if/else is known at compile-time.
是否有可能在编译时不编译错误条件?
Is there any possibility to not compile the false condition at compile-time ?
最简单的解决方法是部分模板特化:
The simplest fix is partial template specialization:
template<typename T> class MyClassBase
{
public:
MyClassBase() : myVar{0} {;}
protected:
T myVar;
};
template<typename T> class MyClass: MyClassBase<T>
{
public:
void testIf() { myVar = 3; }
};
template<typename T> class MyClass<const T>: MyClassBase<const T>
{
public:
void testIf() { myVar; }
};
另一种选择是委托:
template<typename T> class MyClass
{
public:
MyClass() : myVar{0} {;}
void testIf() { testIf_impl(std::integral_constant<bool, isconst>()); }
protected:
static const bool isconst = std::is_const<T>::value;
T myVar;
private:
void testIf_impl(std::true_type) { myvar; }
void testIf_impl(std::false_type) { myVar = 3; }
};
SFINAE 是另一种选择,但通常不适合这种情况:
SFINAE is another option, but is generally not preferred for this case:
template<typename T> class MyClass
{
public:
MyClass() : myVar{0} {;}
template
<typename U = void>
typename std::enable_if<std::is_const<T>::value, U>::type testIf() { myvar; }
template
<typename U = void>
typename std::enable_if<!std::is_const<T>::value, U>::type testIf() { myvar = 3; }
protected:
static const bool isconst = std::is_const<T>::value;
T myVar;
};
这篇关于在 C++ 中编译时的 if/else ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
编译器如何处理编译时分支?What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
在 C/C++ 中检查空指针Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
比较运算符的数学式链接-如“if((5<j<=1))&quMath-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
“if constexpr()"之间的区别与“if()"Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++,'if' 表达式中的变量声明C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)