Hi i am trying to understand how templates work and trying out different examples. I am getting an error while executing the code below. First i am writing the code and then will write what i think is happening.
Code snippet 1:
#include <iostream>
#include<vector>
#include<string>
template<typename It>
auto fcn(It beg, It end) -> decltype(*beg +"name"){ //why isn't decltype(*beg + "name") working here??
return *beg;
}
int main()
{
std::vector<std::string> stringVector = {"firstElement","secondElement"};
std::vector<std::string>::iterator beg = stringVector.begin();
decltype(*beg + "k") l = "anothername";//this is okay and is working here.
std::string s = fcn(stringVector.begin(), stringVector.end());
return 0;
}
While compiling/executing snippet 1 i get an error.
sorry, unimplemented: string literal in function template signature auto fcn(It beg, It end) -> decltype(*beg +"name"){
Here is my explanation of what is happening: The return type of the function template fcn will be deduced from the expression decltype(*beg + "name")
. So *beg
is a reference to the element and in our case *beg
is a reference to string that is string&
and then *beg + "name"
is a rvalue string. So decltype(*beg + "name") will give us a type string
. But inside the definition of the function template fcn we are returning string& and therefore the return type of the function(string) and the type of the value returned from the function(string&) does not match and we get the error. But now as in the 2nd Code snippet i replace return *beg;
with std::string temp = "name"; return temp;
the return type and the type of the returned value should match. The problem is in the 2nd case i am still getting an error. Why am i getting this error and how can i resolve this? Also is my explanation of what is going on correct?
Code Snippet 2:
auto fcn(It beg, It end) -> decltype(*beg +"name"){ //why isn't decltype(*beg + "name") working here??
std::string temp = "name";
return temp;
}
Aucun commentaire:
Enregistrer un commentaire