I've created useful helper method, which looks like this:
template<typename T>
T getRandomItem(vector<T> items){
if(items.isEmpty()) return nullptr;
int i = random(0, (int) items.size() - 1);
return items.at(i);
}
It simply gets random index from vector and return item at that position.
Let me show the first example:
vector<string> v = {"foo", "bar"};
string item = getRandomItem(v);
Compiler doesn't see anything wrong here, but I'm getting very strange linker error:
Undefined symbols for architecture armv7:
"std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > getRandomItem<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >)", referenced from:
Also this doesn't even pass compiler:
auto v = {"foo", "bar"};
string item = getRandomItem(v);
I'm getting following error:
No matching function for call to 'getRandomItem'
Also it doesn't work if I'd like to use it inline:
string item = getRandomItem({"foo", "bar"});
I tried adding before parameters like this:
string item = getRandomItem<string>({"foo", "bar"});
However then I'm getting another compiler error:
Call to 'getRandomItem' is ambiguous.
How can I fix linker error? How should I change my code to pass vector inline?
edit: This example is being compiled by xcode 8.2.1 and random function is from cocos2d-x library (if it does matter).
edit2: After removing template code started compiling:
string getRandomItem(vector<string> items){
if(items.size() == 0) return nullptr;
int i = random(0, (int) items.size() - 1);
return items.at(i);
}
Also I now can do this:
string item = getRandomItem({"foo", "bar"});
So the main question remains: why xcode compiler doesn't allow me to use template here?