【发布时间】:2018-01-05 13:05:50
【问题描述】:
我有一个模板类eglue,它根据传入的参数之一确定自己的n_rows 和n_cols,保证有n_rows 和n_cols 成员。代码如下:
template<typename> struct isEglueOrMat : std::false_type {};
template<typename T1, operations _op, typename T2> struct isEglueOrMat<eglue<T1, _op, T2>> : std::true_type {};
template<> struct isEglueOrMat<Matrix> : std::true_type {};
template<typename T1, operations _op, typename T2>
class eglue {
public:
const T1& First;
const T2& Second;
const unsigned n_rows;
const unsigned n_cols;
eglue(const T1& f, const T2& s) : First(f), Second(s), n_rows(isEglueOrMat<T1>()? f.n_rows:s.n_rows), n_cols(isEglueOrMat<T1>()? f.n_cols:s.n_cols) {}
当我只想从另一个项目中获取n_rows(这将是一个eglue 或Matrix 对象)时,这不起作用,并出现错误request for member 'n_rows' in 'f', which is of non-class type 'const float'。
我尝试过的另一种方法是模板化构造函数:
template<typename Dummy = void, typename Dummy2 = std::enable_if_t<isEglueOrMat<T1>(), Dummy>> eglue(const T1& f, const T2& s) : First(f), Second(s), n_rows(f.n_rows), n_cols(f.n_cols) {}
template<typename Dummy = void, typename Dummy2 = std::enable_if_t<isEglueOrMat<T2>(), Dummy>> eglue(const T1& f, const T2& s) : First(f), Second(s), n_rows(s.n_rows), n_cols(s.n_cols) {}
这会失败并出现错误
type/value mismatch at argument 1 in template parameter list for 'template<bool _Cond, class _Tp> using enable_if_t = typename std::enable_if::type'
template<typename Dummy = void, typename Dummy2 = std::enable_if_t<isEglueOrMat<T1>(), Dummy>> eglue(const T1& f, const T2& s) : First(f), Second(s), n_rows(f.n_rows), n_cols(f.n_cols) {}
^
error: expected a constant of type 'bool', got 'isEglueOrMat<T1>()'
尽管我已经在代码的其他位置成功使用了isEglueOrMat<type>()(如果有必要我会发布这些,但我已经看到它在其他情况下也有效)。
我知道这可能与其他问题重复或相似,但我真的无法让它工作......任何建议将不胜感激。
编辑:我是个白痴,第二种方法无论如何都行不通,因为您不能重载具有相同签名的构造函数.... 有什么方法可以使第一种方法(或任何其他方法!)有效吗?
【问题讨论】:
-
是
isEglueOrMat()constexpr?否则不能作为模板参数使用。 -
我在
template<typename T1, typename T2> std::enable_if_t<(isEglueOrMat<T1>() || isNumeric(T1)) && (isEglueOrMat<T2>() || isNumeric(T2)), eglue<T1, ADD, T2>> operator +(const T1& first, const T2& second) { return eglue<T1, ADD, T2>(first, second); }中使用过它,它编译得非常好......即使它不是 constexpr 我也不明白为什么它会在这里工作而不在那里工作。 -
isNumeric是宏吗?否则我看不出你怎么能使用这个表达式。 -
是的,我已经用
std::is_integral和std::is_floating_point... 再次定义了它,这不是问题。 :// -
你想具体实例化什么?
eglue<float, ..., float>?目前尚不清楚T1/T2可能的“类型”是什么...
标签: c++ templates constructor c++14 sfinae