[英]Any potential problem with using std::is_same_v rather than overload or specialization?
例如,我有这个:
// 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();
}
}
这取决于您的用例。 if constexpr
仅限于函数范围,则意味着您无法在foo.h
为Foo
和bar.h
Bar
定义create
函数,因此您必须同时包含两者。
这不是对if constexpr
的批评,因为它在将相关的通用代码简短并集中在一个地方方面非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.