C++ 如何根据std::is_相同检查返回不同类型
考虑以下代码:C++ 如何根据std::is_相同检查返回不同类型,c++,templates,C++,Templates,考虑以下代码: template<typename T> T foo() { if (std::is_same<T, int>::value) return 5; if (std::is_same<T, std::string>::value) return std::string("bar"); throw std::exception(); } 模板 T foo(){ if(std::is_sa
template<typename T>
T foo() {
if (std::is_same<T, int>::value)
return 5;
if (std::is_same<T, std::string>::value)
return std::string("bar");
throw std::exception();
}
模板
T foo(){
if(std::is_same::value)
返回5;
if(std::is_same::value)
返回标准::字符串(“条”);
抛出std::exception();
}
当使用foo()
调用时,它抛出一个错误无法将'std::uuCxx11::string{aka std::uuCxx11::basic_string}'转换为'int'作为返回
我知道解决方案是使用模板专门化,但我想问的是,通过
std::is_same
?If
s更改为If constexpr
:
template<typename T>
T foo() {
if constexpr (std::is_same<T, int>::value)
return 5;
if constexpr (std::is_same<T, std::string>::value)
return std::string("bar");
throw std::exception();
}
模板
T foo(){
如果constexpr(std::is_same::value)
返回5;
如果constexpr(std::is_same::value)
返回标准::字符串(“条”);
抛出std::exception();
}
在C++17之前,您必须使用模板专业化来模拟这一点:
template<typename T>
T foo()
{
throw std::exception();
}
template <>
int foo<int>() {
return 5;
}
template <>
std::string foo<std::string>() {
return "bar";
}
模板
T foo()
{
抛出std::exception();
}
模板
int foo(){
返回5;
}
模板
std::stringfoo(){
返回“bar”;
}
如果您的real
foo
比这个示例做的工作更多,并且专门化它会导致代码重复,那么您可以引入一个helper函数,它将只封装return
/throw
语句,并专门化它。在C++17编译器之前的版本中,您可以使用标记分派来获得所需的内容
template <typename T> tag_t {};
int foo(tag_t<int> t) { return 5; }
std::string foo(tag_t<std::string> t) { return "bar"; }
template<typename T>
T foo() {
return foo(tag_t<T>());
}
模板标签{};
int foo(tag_t){return 5;}
std::stringfoo(标记){返回“bar”;}
模板
T foo(){
返回foo(tag_t());
}