【发布时间】:2016-11-10 08:41:25
【问题描述】:
给定一个模板类A,我想根据A的模板参数T_lhs和T_rhs定义一个类型T_res:
template< typename T_lhs, typename T_rhs >
class A
{
// definition of T_res in case "T_lhs and T_rhs are both not primitive types"
template< bool lhs_is_fundamental = std::is_fundamental<T_lhs>::value,
bool rhs_is_fundamental = std::is_fundamental<T_rhs>::value,
std::enable_if_t<( !lhs_is_fundamental && !rhs_is_fundamental )>* = nullptr >
using T_res = decltype( std::declval<T_lhs>().cast_to_primitive() / std::declval<T_rhs>().cast_to_primitive() );
// definition of T_res in case "T_lhs and/or T_rhs is a primitive type"
template< bool lhs_is_fundamental = std::is_fundamental<T_lhs>::value,
bool rhs_is_fundamental = std::is_fundamental<T_rhs>::value,
std::enable_if_t<( lhs_is_fundamental || rhs_is_fundamental )>* = nullptr >
using T_res = decltype( std::declval<T_lhs>() / std::declval<T_rhs>() );
// ...
};
在第一种情况下,T_lhs 和 T_rhs 都不是原始类型,我的代码被设计成它们代表实现函数 cast_to_primitive() 的类,该函数返回原始类型;在第一种情况下,我希望 T_res 具有通过将 decltype( std::declval<T_lhs>().cast_to_primitive() ) 类型的元素除以 decltype( std::declval<T_rhs>().cast_to_primitive() ) 类型的元素而获得的类型。
在第二个中,T_lhs 或 T_rhs 是原始类型(甚至两者都是),我希望 T_res 具有通过将 T_lhs 类型的元素除以元素而获得的类型T_rhs 类型的。例如,如果T_lhs 是一个原始类型,我的代码设计为T_rhs 可以隐式转换为T_lhs 类型的元素;这同样适用于T_rhs 是原始的情况。
很遗憾,上面的代码无法编译。错误:
error: template non-type parameter has a different type 'std::enable_if_t<(lhs_is_fundamental || rhs_is_fundamental)> *' (aka 'typename enable_if<(lhs_is_fundamental || rhs_is_fundamental), void>::type *') in template redeclaration
std::enable_if_t<( lhs_is_fundamental || rhs_is_fundamental )>* = nullptr >
^
note: previous non-type template parameter with type 'std::enable_if_t<(!lhs_is_fundamental && !rhs_is_fundamental)> *' (aka 'typename enable_if<(!lhs_is_fundamental && !rhs_is_fundamental), void>::type *') is here
std::enable_if_t<( !lhs_is_fundamental && !rhs_is_fundamental )>* = nullptr >
^
谁能帮我解决这个问题?
【问题讨论】:
-
std::conditional_t<..>可能会有所帮助。 -
了解你的班级
A的目的是什么会有所帮助。