enable_if和相互排斥的方法
enable_if and mutually exclusive methods
我不明白为什么下面的代码不起作用。 编译器(GCC)似乎将两者实例化方法,显然整数要么是有符号的,要么是无符号的,所以总是失败。我虽然enable_if来这里是为了避免这种情况。
问:为什么会出现编译错误,如何避免?
using namespace boost; // or std as you want
template<typename T>
struct test {
// if signed
template< typename enable_if
< is_signed<T>
, int
>:: type = 0
>
test &operator<<=(int value)
{}
// if unsigned
template< typename enable_if
< is_unsigned<T>
, int
>:: type = 0
>
test &operator<<=(int value)
{}
};
void foo()
{
test<int> x;
x << 1; // COMPILE ERROR no type named 'type' in struct enable_if<unsigned> etc.
test<unsigned> y;
y << 1; // COMPILE ERROR no type named 'type' in struct enable_if<int> etc.
}
SFINAE 仅适用于即时上下文(SFINAE = SFIICINAE,即时上下文中的替换失败不是错误):
§14.8.2 [温度扣除]/p8:
只有函数类型及其模板参数类型的直接上下文中的无效类型和表达式才可能导致推导失败。
在成员函数的声明中替换类模板参数不是直接上下文,并且会导致失败时的硬错误。
您可以根据类型对整个类进行部分专用化,也可以通过将模板参数添加到成员函数模板本身来自己引入即时上下文,以便替换失败可能导致软错误:
template <typename U = T, typename std::enable_if<std::is_signed<U>{}, int>::type = 0>
test &operator<<=(int value)
{ return *this; }
template <typename U = T, typename std::enable_if<std::is_unsigned<U>{}, int>::type = 0>
test &operator<<=(int value)
{ return *this; }
相关文章:
- 在 if 语句中处理多个 or 的更优雅的方法是什么
- MSVC使用constexpr-if从可变模板方法中的基本模板参数中吞下const
- 多个 if-else 测试的更简单方法
- 有没有更有效的方法来替换这些多个 IF 语句?
- 在创建完整对象之前编写 if-can-add check 方法的正确方法?
- 一种无需使用if语句而无需使用阈值的方法
- 减少 if-elseif 语句的聪明方法
- 用 c++ 编写一堆类似的 if 语句的漂亮方法
- 有没有更简单的方法可以做到:if(num1 > num2 && num1 > num3),以获得更大的变量列表进行比较?
- 有没有简单的方法可以在 if-else 链的末尾做与 else 相反的事情
- 具有"else if"方法问题 C++ 的基本计算器
- 将字符串中的特定单词与c 中的if或while进行比较的最佳方法
- 适当使用IF Goto循环的方法
- 通过找到一种删除许多 if 语句的方法来简化代码
- C++对方法和What-if所有东西都转到.h的未定义引用
- 将字符串存储在要在 IF 语句中使用的数组中的可能方法
- 不使用 if 插入/更新 std::unordered_map 元素的最快方法是什么
- 编写 if then else 类型语句的简洁方法
- 用c++编写if-then-else语句的更有效方法
- 有更整洁的方法吗?C++IF