I have the following code that fails when I call a bfs
function and pass string
literal as an argument:
template<typename T>
using Graph = unordered_map<T, vector<T> >;
template<typename T>
vector<T> bfs(const Graph<T>& graph, const T& root) {
...
}
int main() {
Graph<string> social_network = {
{"you", {"tony", "steve", "nick"}},
{"tony", {"clint"}},
{"nick", {"thor", "natasha"}},
{"steve", {"phil", "clint"}}
};
bfs(social_network, "you"); <-- the problem is here
}
The error is the following:
Candidate template ignored: deduced conflicting types for parameter 'T' ('std::__1::basic_string<char>' vs. 'char [4]')
if I explicitly specify string
type for the argument, the code compiles successfully:
bfs(social_network, string("you"));
Is there a way to pass a string
literal as an argument and make this code compile as well:
bfs(social_network, "you");
Thanks!
You can make type of root as being ignored in deduction of template parameters by using type_identity_t
(required c++20), then T
is taken from graph
parameter:
const std::type_identity_t<T>& root
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.