enable_if+类型模板,无SFINAE(enable_if_c无boost?)
enable_if + type template, no SFINAE (enable_if_c without boost ?)
我从阅读各种帖子中了解到,以下内容不应该编译。
#include <type_traits>
#include <iostream>
template <bool is_constant> struct A {
// Need to fix this for g++-4.7.2
// implicit conversion to int iff is_constant == true statically
template <class = typename std::enable_if<is_constant>::type>
constexpr operator int() const {
return 10;
}
};
int main()
{
A<true> a;
int i = 2 + a;
std::cout << i << "n";
A<false> b;
// int i = 2 + a; // compilation error
}
尽管如此,clang 3.2还是接受了这个代码版本,并且运行良好。我的理解是,它在后台使用了enable_if_c的内部版本。现在我想在gcc下编译这个,它不接受它。我知道有一个实际的类型并像其他帖子一样使用SFINAE会很好。
就我而言:
- 我正在尝试定义一个运算符,所以我不能对具有某些默认类型/值的额外参数大惊小怪->似乎我不能使用SFINAE
- 我也不能使用继承,因为我必须保持所有常量表达式
- 由于项目要求,我不能在代码中使用任何boost-include(enable_if_c)
我有出路吗?
为什么不使用专业化?
#include <iostream>
template <bool is_constant>
struct A {};
template <>
struct A<true> {
constexpr operator int() const {
return 10;
}
};
int main()
{
A<true> a;
int i = 2 + a;
std::cout << i << "n";
A<false> b;
// int ii = 2 + b; // compilation error
}
这是一种非常直接和跨编译器的方法。。。
相关文章:
- 我的简单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