在C++模板函数中使用类型特征,是否可以将值转换为相同类型的T



我正在尝试编写一个类似的模板函数

template<typename T>
T doSomething() { 
//Code
if (std::is_same<T, int>::value) { 
return getInt();   // A library function returning an int
} else if (std::is_same<T, bool>::value) {
return getBool();  // A library function returning a bool
} else { 
throw;
}
}

它根据给定的模板参数调用不同的函数,并返回一个值,该值在运行时保证与T具有相同的类型。但是,编译器给了我这个错误:'return': cannot convert from 'int' to 'T'我想我可以使用类似reinterpret_cast的东西,但在这种情况下,这似乎是不安全和糟糕的做法。

那么,有没有一种方法可以根据C++中的模板参数从模板函数返回不同的类型?

那么,有没有一种方法可以从模板函数返回不同的类型取决于C++中的模板参数?

是的,您可以使用C++17constexpr if

template<typename T>
T doSomething() { 
//Code
if constexpr (std::is_same<T, int>::value) { 
return getInt();   // A library function returning an int
} else if constexpr (std::is_same<T, bool>::value) {
return getBool();  // A library function returning a bool
} else { 
throw;
}
}

除了constexpr if(对于c++17之前的版本(,您还可以使用显式专业化,如下所示:

template<typename T> //primary template
T doSomething() { 
std::cout<<"throw version"<<std::endl;
throw;
}
template<> //specialization for int
int doSomething<int>() { 
std::cout<<"int version"<<std::endl;
return getInt();
}
template<>//specialization for bool
bool doSomething<bool>() { 
std::cout<<"bool version"<<std::endl;
return getBool();
}

演示。

相关内容

最新更新