Moc*_*han 1 c++ type-traits enable-if
我想使用type_traits通过shared_ptr进行过载。
struct A {
A(int i) : x(i) {}
int x;
};
int main()
{
A a{4};
auto b = std::make_shared<A>(7);
A& c = a;
A* d = b.get();
A* e = &a;
std::cout << getX(a) << std::endl;
std::cout << getX(b) << std::endl;
std::cout << getX(c) << std::endl;
std::cout << getX(d) << std::endl;
std::cout << getX(e) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是一种解决方案,但是存在必须预先定义返回类型的问题。
template <typename T>
typename std::enable_if_t<!boost::has_dereference<T>::value, int> getX(T t)
{
return t.x;
}
template <typename T>
typename std::enable_if_t<boost::has_dereference<T>::value, int> getX(T t)
{
return t->x;
}
Run Code Online (Sandbox Code Playgroud)
但是使用下面的方法,我可以设置返回类型,auto但是看起来有点笨拙。
template <typename T, typename std::enable_if_t<!boost::has_dereference<T>::value>* = nullptr>
auto getX(T t)
{
return t.x;
}
template <typename T, typename std::enable_if_t<boost::has_dereference<T>::value>* = nullptr>
auto getX(T t)
{
return t->x;
}
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以使用第一种类型并仍然获得返回类型auto?
我不想指定类型,A::x因此auto返回类型将是最佳选择。第二种做到了,但感觉有些笨拙。
还是有更好的方法呢?谢谢。
If you just want to run a different line of code or two for different types then constexpr if lets you do that without having to use enable_if and allows you to use automatic return type deduction. You can simplify getX into
template <typename T>
auto getX(T t)
{
if constexpr (boost::has_dereference<T>::value)
return t->x;
else
return t.x;
}
Run Code Online (Sandbox Code Playgroud)
and this works because the path that is not executed is discarded so at compile time only the true path compiled.