[英]Unpacking arguments of a functional parameter to a C++ template class
I have a question involving functional template arguments to template classes in C++. 我有一个问题涉及C ++中模板类的函数模板参数。
I'd like to define a template class Foo
taking a single template parameter Fun
我想定义一个模板类
Foo
它采用单个模板参数Fun
template <typename Fun>
struct Foo {
...
};
such that given a function like 这样的功能就像
void bar(std::string a, float b, char c)
{
...
}
then Foo<bar>::args_t
will be equivalent to a typedef for 那么
Foo<bar>::args_t
将等同于一个typedef
std::tuple<std::string, float, char>
Is this possible? 这可能吗? (The use of
std::tuple
here is just for concreteness. More generally I'm wondering if it's possible to do something like pattern-matching on the arguments of a functional template parameter.) (这里使用
std::tuple
只是为了具体。更一般地说,我想知道是否可以对函数模板参数的参数进行模式匹配等操作。)
The point is to avoid having to define Foo
in a way like 重点是避免以某种方式定义
Foo
template Foo<typename A, typename B, typename C, typename D,
D (*Fun)(A a, B b, C c)>
struct Foo {
typedef std::tuple<A,B,C> args_t;
};
which requires both committing to a fixed number of function arguments, and requiring the argument and return types of the function to be provided explicitly as template parameters. 这需要提交到固定数量的函数参数,并要求函数的参数和返回类型作为模板参数显式提供。 (Defining
Foo
using variadic templates could presumably solve the former issue, but what about the latter?) (使用可变参数模板定义
Foo
可能会解决前一个问题,但后者呢?)
Thanks! 谢谢!
Declare a primary template and leave it unimplemented. 声明主模板并使其未实现。
template<typename T>
struct foo; // unimplemented primary template
Then provide a partial specialization that matches function types as the template argument. 然后提供一个部分特化,将函数类型作为模板参数进行匹配。
template<typename Result, typename... Args>
struct foo<Result(Args...)>
{
using args_t = std::tuple<Args...>;
};
You can access the nested type as 您可以访问嵌套类型
foo<decltype(bar)>::args_t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.