使用 C++ 类型特征,是否有一些方法可以避免强制转换
With C++ type-traits, is there some way to avoid casting
假设我在方法模板中使用 C++ 类型特征来检查 T 是否为双精度,是否有某种方法可以将 T 类型的变量视为双精度而不进行转换?
T *l_double; //T is double
if T is of type double
auto a = 5 * (*l_double);
(这会失败,因为 T 可以是非数字类型,我可以通过转换来解决它,但我想避免它)。
如果我正确理解你的问题,你想要的是 T
是 double
的情况的专业化。好吧,就这么做——不涉及类型特征:
template <typename T>
void foo(T x) { /* do something with x */ }
template <>
void foo<double>(double x) { /* do something _else_ with x */ }
或者如果你使用C++17,你也可以这样做:
template <typename T>
void foo(T x) {
if constexpr (not std::is_same_v<double,T>) {
/* do something with x */
}
else {
/* do something with else x */
}
}
注意 if
之后的 constexpr
。这意味着每个块中的代码只会针对适当的实例进行编译;没有它,您不能在 else
块中将 x
用作双精度数,因为当 x
是另一种类型时,这种用法也必须起作用。
假设我在方法模板中使用 C++ 类型特征来检查 T 是否为双精度,是否有某种方法可以将 T 类型的变量视为双精度而不进行转换?
T *l_double; //T is double
if T is of type double
auto a = 5 * (*l_double);
(这会失败,因为 T 可以是非数字类型,我可以通过转换来解决它,但我想避免它)。
如果我正确理解你的问题,你想要的是 T
是 double
的情况的专业化。好吧,就这么做——不涉及类型特征:
template <typename T>
void foo(T x) { /* do something with x */ }
template <>
void foo<double>(double x) { /* do something _else_ with x */ }
或者如果你使用C++17,你也可以这样做:
template <typename T>
void foo(T x) {
if constexpr (not std::is_same_v<double,T>) {
/* do something with x */
}
else {
/* do something with else x */
}
}
注意 if
之后的 constexpr
。这意味着每个块中的代码只会针对适当的实例进行编译;没有它,您不能在 else
块中将 x
用作双精度数,因为当 x
是另一种类型时,这种用法也必须起作用。