带有元组与非元组变体的函数模板
我需要一个模板,它可以有多种返回类型:要么是单一类型,例如 std::string,要么是一个包含两种及以上不同类型的 std::tuple。
当下方代码中的行被取消注释时,编译器将给出以下响应:
Call to getValue is ambiguous。
#include <iostream>
#include <tuple>
template<class ReturnType>
ReturnType getValue(const char* arg) {
throw std::runtime_error("Unknown ReturnType");
}
template<>
std::string getValue(const char* arg) {
return std::string(arg);
}
template<>
int getValue(const char* arg) {
return std::atoi(arg);
}
// template<class... ReturnTypes>
// std::tuple<ReturnTypes...> getValue(const char* arg) {
// std::tuple<ReturnTypes...> return_tuple;
// std::cout << "Return tuple size: " << sizeof...(ReturnTypes) << std::endl;
// return return_tuple;
// }
int main() {
auto int_val = getValue<int>("73");
std::cout << "int_val: " << int_val << std::endl;
// auto toople = getValue<std::tuple<int, std::string>>("onions");
return 0;
}
期望输出:
int_val: 73
返回的元组大小:2
解决方案
对于这种函数,我会使用带有常规参数的中间函数:
std::string getValueImpl(std::type_identity<std::string>, const char* arg) {
return std::string(arg);
}
int getValueImpl(std::type_identity<int>, const char* arg) {
return std::atoi(arg);
}
template <typename... Ts>
std::tuple<Ts...> getValueImpl(std::type_identity<std::tuple<Ts...>>, const char* arg) {
std::tuple<Ts...> return_tuple;
std::cout << "Return tuple size: " << sizeof...(Ts) << std::endl;
return return_tuple;
}
// Possible fall back
template <typename T>
void getValueImpl(std::type_identity<T>, const char* arg) = delete;
template<class ReturnType>
ReturnType getValue(const char* arg) {
return getValueImpl(std::type_identity<ReturnType>{}, args);
}
你的问题在于 getValue<int> 可能要么是
template<T> T getValue(const char* arg),带有T=int- 或者
template<class... Ts> std::tuple<Ts...> getValue(const char* arg),Ts...=int
没有一个重载更具体。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。