[英]Function template taking a template non-type template parameter
如何将模板指针作为成员函数?
通过模板化我的意思是事先不知道以下类型:
T
是指向成员的指针的类 R
是返回类型 Args...
是参数 用于说明问题的非工作代码:
template <???>
void pmf_tparam() {}
// this works, but it's a function parameter, not a template parameter
template <class T, typename R, typename... Args>
void pmf_param(R (T::*pmf)(Args...)) {}
struct A {
void f(int) {}
};
int main() {
pmf_tparam<&A::f>(); // What I'm looking for
pmf_param(&A::f); // This works but that's not what I'm looking for
return 0;
}
是否有可能在C ++ 11中实现所需的行为?
我认为这种符号是不可能的。 建议P0127R1使这种表示法成为可能。 模板将声明如下:
template <auto P> void pmf_tparam();
// ...
pmf_tparam<&S::member>();
pmf_tparam<&f>();
为非类型参数添加auto
的提议被投票到Oulu的C ++工作文件中,结果被投票成为在Oulu中也导致C ++ 17的CD 。 如果没有非类型参数的auto
类型,则需要提供指针的类型:
template <typename T, T P> void pmf_tparam();
// ...
pmf_tparam<decltype(&S::member), &S::member>();
pmf_tparam<decltype(&f), &f>();
正如你在功能中没有真正说过的那样,最简单的是:
struct A {
void bar() {
}
};
template <typename T>
void foo() {
// Here T is void (A::*)()
}
int main(void) {
foo<decltype(&A::bar)>();
}
但是,如果您希望签名被分解,我不确定是否有办法直接解决这些类型,但是您可以稍微间接...
struct A {
void bar() {
std::cout << "Call A" << std::endl;
}
};
template <typename R, typename C, typename... Args>
struct composer {
using return_type = R;
using class_type = C;
using args_seq = std::tuple<Args...>;
using pf = R (C::*)(Args...);
};
template <typename C, typename C::pf M>
struct foo {
static_assert(std::is_same<C, composer<void, A>>::value, "not fp");
typename C::return_type call(typename C::class_type& inst) {
return (inst.*M)();
}
template <typename... Args>
typename C::return_type call(typename C::class_type& inst, Args&&... args) {
return (inst.*M)(std::forward<Args...>(args...));
}
};
template <class T, typename R, typename... Args>
constexpr auto compute(R (T::*pmf)(Args...)) {
return composer<R, T, Args...>{};
}
int main() {
foo<decltype(compute(&A::bar)), &A::bar> f;
A a;
f.call(a);
}
以上应该做你想做的事......
你能做的是
template <template T, T value>
void pmf_tparam() {}
然后
pmf_tparam<decltype(&A::f), &A::f>();
问题是不知道参数的类型并且想要该类型的模板参数。
使用额外的decltype
(仍然在模板化参数中),这有效:
#include <iostream>
using namespace std;
template <typename T, T ptr>
void foo (){
ptr();
}
void noop() {
cout << "Hello" << endl;
}
int main() {
//Here have to use decltype first
foo<decltype(&noop), noop>();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.