【发布时间】:2014-11-25 10:45:49
【问题描述】:
这更像是一个概念性问题。我试图找到将双参数模板(参数是类型)转换为单参数模板的最简单方法。即,绑定其中一种类型。
这将是 boost/std 中 bind 的元编程等价物。我的示例包括一个可能的用例,即将std::is_same 作为模板参数传递给采用单参数模板模板参数(std::is_same 是双参数模板)的模板,即传递给TypeList::FindIf。 TypeList 在这里没有完全实现,FindIf 也没有,但你明白了。它接受一个“一元谓词”并返回该谓词为真的类型,如果不是这种类型,则返回void。
我有 2 个工作变体,但第一个不是单行,第二个使用相当冗长的 BindFirst 装置,这不适用于非类型模板参数。有没有一种简单的方法来编写这样的单行代码?我相信我正在寻找的程序称为currying。
#include <iostream>
template<template<typename, typename> class Function, typename FirstArg>
struct BindFirst
{
template<typename SecondArg>
using Result = Function<FirstArg, SecondArg>;
};
//template<typename Type> using IsInt = BindFirst<_EqualTypes, int>::Result<Type>;
template<typename Type> using IsInt = std::is_same<int, Type>;
struct TypeList
{
template<template<typename> class Predicate>
struct FindIf
{
// this needs to be implemented, return void for now
typedef void Result;
};
};
int main()
{
static_assert(IsInt<int>::value, "");
static_assert(!IsInt<float>::value, "");
// variant #1: using the predefined parameterized type alias as predicate
typedef TypeList::FindIf<IsInt>::Result Result1;
// variant #2: one-liner, using BindFirst and std::is_same directly
typedef TypeList::FindIf< BindFirst<std::is_same, int>::Result>::Result Result2;
// variant #3: one-liner, using currying?
//typedef TypeList::FindIf<std::is_same<int, _>>::Result Result2;
return 0;
}
点击here在线编译GodBolt中的代码。
【问题讨论】:
-
既然我相信答案是“不,没有更简单的方法”,我当然会接受任何提供一些有用信息的答案(例如计划可能在标准中包含这样的东西)。
标签: c++ templates metaprogramming bind currying