假设我想知道类型是否是Eigen
对象,而不是原语或其他类。如何在不实际投射对象的情况下实现此目的?
template <typename Derived>
EigenBase<Derived> fun(const EigenBase<Derived>& value)
{
// This is bad, because value is now of type EigenBase<Derived> and I don't know
// what the original type is.
return value;
}
template <typename T>
T fun(const T& value)
{
// This will also catch primitives and other classes.
return value;
}
如何才能捕获仅类型,这些类型可以被类型推导到Eigen::EigenBase<T>
,而不会实际将它们转换为该类型?
答案 0 :(得分:2)
您可以使用SFINAE和std::is_base_of
:
template <typename T>
typename std::enable_if<std::is_base_of<EigenBase<T>, T>::value, T>::type
fun(const T& value)
{
// This will be enabled only for class which derive from EigenBase<T>.
return value;
}
答案 1 :(得分:2)
在第一个版本中,执行表达式类型为Derived
,您可以通过.derived()
成员获取它:
template <typename Derived>
typename Derived::PlainObject fun(const EigenBase<Derived>& a_value)
{
const Derived &value(a_value.derived()); // the actual expression object
typename Derived::PlainObject ret; // this is an object with storage, typically the Matrix<> type closest to Derived.
ret = 2*value;
return ret;
}
此外,你永远不应该按价值返回,更常见的是,创建一个EigenBase&lt;&gt;宾语。 EigenBase根本没有存储空间,它就像一个抽象的基类。
答案 2 :(得分:0)
template<typebame T>
class IsEigen
{
public:
enum
{
value = 0;
}
};
template<>
class IsEigen<Eigen>
{
public:
enum
{
value = 1;
}
};
template<typename Derived>
EigenBase<Derived> fun(const EigenBase<Derived>& value)
{
if(IsEigen<Derived>::value)
{
...
}
else
{
...
}
...
}