首页 > 解决方案 > 仅绑定到一种类型的转发引用?

问题描述

我想要一个只绑定到一种类型的转发引用。我可以使用静态断言,但我想知道是否有更优雅的(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++c++14perfect-forwarding

解决方案


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.


推荐阅读