c++ - 仅绑定到一种类型的转发引用?
问题描述
我想要一个只绑定到一种类型的转发引用。我可以使用静态断言,但我想知道是否有更优雅的(C++14/17)方法来做到这一点。
这里有一个例子:
#include <iostream>
#include <string>
#include <type_traits>
template<class T>
void f(T&& x) {
// Is there a more elegant way to check for the type than the static_assert?
static_assert(std::is_same<std::string, typename std::remove_cv_t<std::remove_reference_t<T>>>::value);
x = x + "Bar";
std::cout << x << std::endl;
}
int main()
{
std::string name("Foo");
f(name);
f(std::move(name));
}
解决方案
C++20 方式:
template <typename T>
requires std::same_as<std::string, std::remove_cvref_t<T>>
void f(T &&x) {}
C++17 方式:
template <
typename T,
std::enable_if_t<
std::is_same_v<
std::string,
std::remove_cv_t<std::remove_reference_t<T>>
>,
std::nullptr_t
> = nullptr
>
void f(T &&x) {}
C++14 的方式与 C++17 相同,只是你必须std::same_as<...>::value
使用std::is_same_v
.
推荐阅读
- asp.net - 我想在 asp.net 中输入文本框触发服务器端事件
- javascript - router.put 不工作,app.put 工作正常
- android - 如果两个不同的异步回调启动两个不同的同步方法会发生什么?
- android - 仅使用 TCP 通信的 AOSP SystemService
- ruby - “get_binding”未定义方法“id”
- java - 如何使用 MQTT 从 Swing Java 应用程序向服务器发送/接收数据
- javascript - onClientClick return Function() 仍然会触发 OnClick
- javascript - 将jsp变量传递给javascript
- java - 如何从 textarea 获取文本并将其作为 URL 的参数发送
- terminal - 如何在特定窗格中使用特定命令启动 Iterm?