【发布时间】:2019-06-04 13:07:28
【问题描述】:
我有一段相当复杂的代码,我将其简化为这个复制器:
#include <type_traits>
#include <tuple>
template<typename ...As>
struct outer {
template<typename ...Bs>
struct inner {
template<bool dummy, typename E = void>
struct problem;
using TA = std::tuple<As...>;
using TB = std::tuple<Bs...>;
template<bool dummy>
struct problem<dummy, typename std::enable_if<std::tuple_size<TA>::value < std::tuple_size<TB>::value>::type>
{
static constexpr auto val() { return 1; } // actually a complex function
};
template<bool dummy>
struct problem<dummy, typename std::enable_if<std::tuple_size<TA>::value >= std::tuple_size<TB>::value>::type>
{
static constexpr auto val() { return 0; }
};
};
};
int main() {
return outer<int, float>::inner<double>::problem<false>::val();
}
它不编译(使用 gcc 或 clang),说:
<source>:13:82: error: failed requirement 'std::tuple_size<std::tuple<int, float> >::value < std::tuple_size<std::tuple<double> >::value'; 'enable_if' cannot be used to disable this declaration
struct problem<dummy, typename std::enable_if<std::tuple_size<TA>::value <std::tuple_size<TB>::value>::type>
~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:27:31: note: in instantiation of template class 'outer<int, float>::inner<double>' requested here
return outer<int, float>::inner<double>::problem<false>::val();
我尝试了一些变体,但没有任何效果。
我阅读了一些已经发布的问答,例如: this one 或this one 但他们似乎没有回答我的问题。
PS:我可以使用 C++17,但它必须适用于任何编译器。
【问题讨论】:
-
原因是需求不是
problem的实例化中的依赖表达式。在这个具体的例子中,可以让val只返回std::tuple_size<std::tuple<int, float> >::value < std::tuple_size<std::tuple<double> >::value ? 1 : 0。 -
不,这是不可能的。 val 实际上是一个复杂的函数
-
您可能想查看“if constexpr”,这会产生比 enable_if 更简单的代码。
标签: c++ variadic-templates inner-classes sfinae typetraits