在 C++ 中转发引用和转换构造函数
Forwarding references and converting constructors in C++
假设我想创建一个函数,通过引用获取左值和右值字符串参数,将它们转换为大写,并将它们打印到标准输出:
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_if
或 static_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);
}
假设我想创建一个函数,通过引用获取左值和右值字符串参数,将它们转换为大写,并将它们打印到标准输出:
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_if
或 static_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);
}