gpt4 book ai didi

c++ - 在 C++ 中转发引用和转换构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:47:07 24 4
gpt4 key购买 nike

假设我想创建一个函数,通过引用获取左值和右值字符串参数,将它们转换为大写,并将它们打印到标准输出:

void upper_print(std::string& s);
void upper_print(std::string&& s);

这工作正常,如下所示:

std::string s("Hello world");
upper_print(s);
upper_print(std::string("Hello world"));
upper_print("Hello world"); // converting ctor used

但是,为了避免冗余,我想改用转发引用:

template <typename T> upper_print(T&& s);

不幸的是,我无法使用字符串文字参数调用 upper_print:

std::string s("Hello world"); // OK
upper_print(s); // OK
upper_print(std::string("Hello world")); // OK
upper_print("Hello world"); // ERROR

我知道可以将参数限制为 std::string 对象,例如,通过使用 std::enable_ifstatic_assert .但这对这里没有帮助。

在这个意义上是否有任何选项可以结合转发引用和转换构造函数的功能?

最佳答案

也许是这样的解决方案?

template <typename T>
void upper_print_helper(T&& s);

inline void upper_print(std::string&& s) {
upper_print_helper(std::move(s));
}
inline void upper_print(std::string& s) {
upper_print_helper(s);
}

关于c++ - 在 C++ 中转发引用和转换构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45029913/

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