元函数重载 C++ - enable_if
metafunction overload C++ - enable_if
假设我想有 2 个名为乘法的元函数。这些元函数应该对向量类型进行操作。
- 一个
元函数应将两个向量作为输入,并将一个值乘以另一个值
另一个应该将一个向量和标量作为输入,并将向量中的所有值乘以标量。
我想编译的代码:
template <int V1, int V2, int V3...>
struct vector_c{
enum{
v1 = V1,
v2 = V2,
v3 = V3,
///
};
};
template <typename Vector1, typename Vector2>
struct multiplicate{
typedef /* do stuff */ type;
};
template <typename Vector1, int value>
struct multiplicate{
typedef /* do stuff */ type;
};
问题是,这段代码无法编译。我想做一些类似的事情:
template <typename Vector1, typename Vector2,
typename enable_if_c<is_vector<Vector2>::value, int>::type =0>
struct multiplicate{
typedef /* do stuff */ type;
}; //should be fine
template <typename Vector1, int value,
typename enable_if_c // what now? >
struct multiplicate{
//stuff
};
问题是,在第二种情况下,我不能把任何东西放在enable_if,因为值不是一个类型,但它已经是 int 类型的值。如何使此代码工作?
您需要使用模板专用化,而不是两个不同的模板。
//Primary template forward declaration
template<typename Vector1, typename Vector2, typename Enable = void>
struct multiplicate;
//specialization when is_vector<Vector2> is true
//leave second argument of enable_if with default value!!!
template<typename Vector1, typename Vector2>
struct multiplicate<Vector1, Vector2,
typename enable_if<is_vector<Vector2>::value>::type>
{ //do the stuf
};
//specialization when Vector2 is exactly type int
template<typename Vector1, typename Vector2>
struct multiplicate<Vector1, Vector2,
typename enable_if<is_same<Vector2, int>::value>::type>
{ //do the stuf
};
/* Declaration for any other case!
when you comment it (or delete), compilation fails
for other types of Vector2 with error: incomplete type */
template<typename Vector1, typename Vector2, typename Enable>
struct multiplicate
{ //do the stuf
};
祝您编码愉快!
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- 为什么简单的算术减法在"if"条件下不起作用?
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- SFINAE with boost enable if