我从阅读各篇文章中了解到以下内容不应该编译。
#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。
就我而言:
我有出路吗?
答案 0 :(得分:0)
为什么不使用专业化?
#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
}
这是非常简单和交叉编译的方法......