【发布时间】:2014-10-19 03:34:10
【问题描述】:
我想创建一个元函数,如果传递给它的参数超过 1 个,则返回特定类型,如果只传递一个参数,则返回基于条件的另一种类型。条件是任意的,所以它需要enable_if 或类似的东西,但在这个例子中,我只做一个类型比较。让我们将其简化为以下内容
- 如果传递了单个参数并且该参数是
int,则返回bool - 如果传递了单个参数并且该参数是
double,则返回int - 如果传递了多个参数,则返回
double
为了实现这一点,我尝试了以下操作:
#include <type_traits>
template <typename Enable, typename...Args>
struct Get;
// multiple arguments; return double regardless of the condition
template <typename FirstArg, typename... OtherArgs>
struct Get<typename std::enable_if<true>::type, FirstArg, OtherArgs...>
{
using type = double;
};
// single int; return bool
template <typename Arg>
struct Get<typename std::enable_if<std::is_same<Arg, int>::value>::type, Arg>
{
using type = double;
};
// single double; return int
template <typename Arg>
struct Get<typename std::enable_if<std::is_same<Arg, double>::value>::type, Arg>
{
using type = int;
};
int main()
{
static_assert(std::is_same<typename Get<double>::type, int>::value, "");
static_assert(std::is_same<typename Get<int>::type, bool>::value, "");
static_assert(std::is_same<typename Get<bool, int>::type, double>::value, "");
return 0;
}
输出:
prog.cpp: In function ‘int main()’: prog.cpp:29:51: error: ‘type’ in ‘struct Get<double>’ does not name a type static_assert(std::is_same<typename Get<double>::type, int>::value, ""); ^ prog.cpp:29:60: error: template argument 1 is invalid static_assert(std::is_same<typename Get<double>::type, int>::value, "");
我会很感激能教我为什么这不能按我预期的方式工作的答案,而不仅仅是如何解决它。我一直在努力寻找关于模板元编程的好资源,并且到目前为止我的编程相当随意,这是我非常想解决的问题!
【问题讨论】:
-
你需要的是这个webpage
-
这里根本不需要
enable_if:coliru.stacked-crooked.com/a/79314b2d15824360(多个参数特化实际上可以是主模板中的static_assert)。 -
@dyp 我试图创建一个简化的示例,
enable_if应该代表任意条件。我已经编辑了问题以使其更清楚。 -
即便如此,我也不确定您是否需要
enable_if本身;您也可以将条件(作为类型函数)与默认为std::true_type的模板参数匹配。 (有人可能会说使用enable_if更清晰。)