问题描述
考虑以下代码:
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();
}
当使用 foo< int>()
调用时,会引发错误无法转换'std :: __ cxx11 :: string {aka std :: __ cxx11 :: basic_string< char>}'到'int'作为回报
.
When called with foo<int>()
, it throws an error cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘int’ in return
.
我知道解决方案是使用模板专业化,但是我在问是否可以通过 std :: is_same
检查类型来保持当前机制?
I know the solution is to use template specialization, but I'm asking whether it is somehow possible to keep the current mechanism with checking the type via std::is_same
?
推荐答案
if
的两个分支在编译时都必须有效,即使其中一个分支从未执行过.
Both branches of an if
must be valid at compile-time, even if one of them is never executed.
如果可以访问C ++ 17,请将 if
s更改为 if constexpr
:
If you have access to C++17, change the if
s to 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();
}
在C ++ 17之前,您将必须使用模板专门化来对此进行仿真:
Before C++17, you will have to emulate this by using template specialisation:
template<typename T>
T foo()
{
throw std::exception();
}
template <>
int foo<int>() {
return 5;
}
template <>
std::string foo<std::string>() {
return "bar";
}
如果真正的 foo
所做的工作比该示例更多,并且专门化它会导致代码重复,则可以引入一个辅助函数,该函数将仅封装 return
/抛出
语句,并将其专门化.
If your real foo
does more work than this example and specialising it would lead to code duplication, you can introduce a helper function which will encapsulate only the return
/throw
statements, and specialise that.
这篇关于如何基于std :: is_same检查返回不同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!