gpt4 book ai didi

c++ - 使用 std::is_same_v 而不是重载或特化有任何潜在问题吗?

转载 作者:行者123 更新时间:2023-12-04 11:32:54 24 4
gpt4 key购买 nike

例如,我有这个:

// Code A
int create_int() { return 42; }
double create_double() { return 3.14; }
std::string create_string() { return {"Hi"}; }

现在让我们假设将这些 create 放在一起是有意义的,所以我重写了代码:

// Code B
template <typename T> T create();
template <> int create<int>() { return 42; }
template <> double create<double>() { return 3.14; }
template <> std::string create<std::string>() { return {"Hi"}; }

甚至:

// Code C
#include <type_traits>

template <typename T> T create()
{
if constexpr (std::is_same_v<T, int>)
{
return 42;
}
else if constexpr (std::is_same_v<T, double>)
{
return 3.14;
}
else if constexpr (std::is_same_v<T, std::string>)
{
return {"Hi"};
}
else
{
// static_assert(false);
return static_cast<T>(0);
}
}

我想知道这些代码之间有什么区别,还是仅仅是代码风格。

最佳答案

它们之间存在语义差异。您不能像本例中那样在通用算法中使用 Code A 函数:

template <class T>
T generic_function() {
return create<T>();
}

因此我更喜欢代码 B 而不是代码 A。

如果您需要在通用算法中采用不同的路径,则 constexpr if 很有用。它使您免于创建重载的辅助函数或更糟糕的构造。

一个例子是为 void 采用不同于其他数据类型的不同路径,因为您不能将 void 作为参数传递给函数。假设您采用一个函数并希望将 std::promise 的值设置为结果。该函数可能没有返回值,但您仍想执行该函数。在这种情况下,constexpr if 将使您免于许多令人头疼的模板元编程。

template <class Fn>
void my_function(Fn fn) {
std::promise<decltype(fn())> promise;

if constexpr(!std::is_same_v<void, decltype(fn())>) {
promise.set_value(fn());
} else {
fn();
promise.set_value();
}
}

关于c++ - 使用 std::is_same_v 而不是重载或特化有任何潜在问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60856358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com