假设我有一个函数的模板,比如说
template<typename T>
func(T a, T b, ...) {
...
for (const auto &single : group) {
...
auto c = GivenFunc1(a, b, single, ...);
... }
...
}
但是,由于 T 是一种特殊类型,比如“SpecialType”,我希望 c
由“GivenFunc2”而不是“GivenFunc1”计算。但是,我不想为“SpecialType”写一个特化,因为会有大量的代码重复。所以我希望模板函数类似于
template<typename T>
func(T a, T b, ...) {
...
for (const auto &single : group) {
...
auto c = (T == SpecialType) ? GivenFunc2(a, b, single, ...)
: GivenFunc1(a, b, single, ...);
... }
...
}
当然,此代码无法编译,因为“T == SpecialType”无效。那么如何优雅地写呢?
最佳答案
很简单:
auto c = std::is_same_v<T, SpecialType> ? GivenFunc2(a, b, single, ...)
: GivenFunc1(a, b, single, ...);
如果不能使用 C++17,请替换 std::is_same_v<...>
与 std::is_same<...>::value
.
但是要使这种方法起作用,两个函数调用都必须对每个 T
都有效。你想使用,即使实际上其中一个不会被执行。
如果不是这样,您可以求助于 if constexpr
:
your_type_here c;
if constexpr (std::is_same_v<T, SpecialType>)
c = GivenFunc2(a, b, single, ...);
else
c = GivenFunc1(a, b, single, ...);
(这只适用于 C++17。)
关于c++ - 如何在 C++ 中比较两个类型名是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51916198/