【发布时间】:2019-01-11 06:15:26
【问题描述】:
如何编写一个使用函数作为模板参数的模板,并通过该函数的参数类型自动推断出其他类型名?
void foo(int *p) {}
template<typename T, void (*F)(T*)>
struct bar
{
bar(T* t)
{
F(t);
}
}
int *p;
bar<int, foo> b(p); // both int and foo are required here
如何编写支持仅使用foo 作为参数的模板
bar<foo> b(p);
【问题讨论】:
-
就我所见(承认不是很近),你不能。
T处于不可演绎的上下文中。您可以使F成为类型化模板参数(与您现在拥有的非类型化参数相反),然后通过模板将推导移至构造函数。我得考虑一会儿。即使在这种情况下,您也需要在b的 decl 上使用 decltype。 -
你需要一个
auto模板参数,它需要 C++17。 -
@n.m.如果你的意思是
template<void (*F)(auto)> struct bar,那么 g++ 给了我error: ‘auto’ parameter not permitted in this context -
不,这不是 auto 的工作方式。 coliru.stacked-crooked.com/a/3f589f17e8bfd766 是一种方法。
-
谢谢@n.m。那行得通,但是如果没有c ++ 17会更好。更喜欢 c++11 > c++14 > c++17