假设我想创建一个函数,通过引用获取左值和右值字符串参数,将它们转换为大写,并将它们打印到标准输出:
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
。但这并没有帮助。
在这个意义上,是否有任何选项可以结合转发引用和转换构造函数的功能?
答案 0 :(得分:0)
也许是这样的解决方案?
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);
}