我想编写一个接受右值和左值引用的可变参数模板函数。它将大写 std::strings,并在大写后显示每个参数。函数结束后,所有左值都应保持大写(即通过引用传递左值)。
例如,我想要这种行为:
std::string hello = "hello";
std::string planet = "planet";
std::string earth = "earth";
//the order and amount of rvalues and lvalue references, should not matter
Capitalize_And_Output("hello","planet","earth"); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output(hello,"planet","earth"); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output("hello",planet,"earth"); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output("hello","planet",earth); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output(hello,planet,"earth"); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output(hello,"planet",earth); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output("hello",planet,earth); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output(hello,planet,earth); //outputs: "HELLO PLANET EARTH"
//lvalue references remain changed after the function call
std::cout << hello << std::endl; //outputs: "HELLO"
std::cout << planet << std::endl; //outputs: "PLANET"
std::cout << earth << std::endl; //outputs: "WORLD"
我怎样才能得到上面的代码块来编译和工作,如图所示?
到目前为止,我能够输出信息,但我不知道如何处理两种不同值类型的大写。以下代码将编译,因为我已经注释掉了不起作用的行。
#include <string>
#include <iostream>
#include <algorithm>
template<typename T>
void Capitalize_And_Output(T & str) {
//std::transform(str.begin(), str.end(), str.begin(), ::toupper); <- will not compile
std::cout << str<< std::endl;
return;
}
template<typename First, typename ... Strings>
void Capitalize_And_Output(First & str, const Strings&... rest) {
//std::transform(str.begin(), str.end(), str.begin(), ::toupper); <- will not compile
std::cout << str << " ";
Capitalize_And_Output(rest...);
return;
}
int main() {
std::string hello = "hello";
std::string planet = "planet";
std::string earth = "earth";
//the order and amount of rvalues and lvalue references, should not matter
Capitalize_And_Output("hello","planet","earth"); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output(hello,"planet","earth"); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output("hello",planet,"earth"); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output("hello","planet",earth); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output(hello,planet,"earth"); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output(hello,"planet",earth); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output("hello",planet,earth); //outputs: "HELLO PLANET EARTH"
Capitalize_And_Output(hello,planet,earth); //outputs: "HELLO PLANET EARTH"
//lvalue references keep changed value after the function call
std::cout << hello << std::endl; //outputs: "HELLO"
std::cout << planet << std::endl; //outputs: "PLANET"
std::cout << earth << std::endl; //outputs: "WORLD"
return 0;
}
我怎样才能让它工作?
也许转换函数不起作用,因为右值实际上是不同的类型?它们是 char*s?
我脑子里在想什么:
我必须对类型特征做些什么吗?
有 R 值参考的东西?
具有普遍敬意的东西(虽然不太确定那是什么)?
请更正术语的任何滥用!