C ++中有什么方法可以在不调用函数模板或不提供其模板参数的情况下引用它? [英] Is there any way in C++ to refer to a function template while neither calling it nor supplying its template parameters?

查看:161
本文介绍了C ++中有什么方法可以在不调用函数模板或不提供其模板参数的情况下引用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要工作的代码:

template <class T> void Foo(T&& param);

template <class F> void CallMe(F&& func)
{
    func(42);
}

int main()
{
    CallMe(Foo);
}

编译器尝试实例化 CallMe ,因为它不知道我所说的 Foo 。如果我写 Foo< int> 当然可以,但是我想避免这种情况,因为在实际代码中模板参数可能很复杂。

The compiler chokes when it tries to instantiate CallMe because it doesn't know what I mean by Foo. It works if I write Foo<int> of course, but I'd like to avoid that because in the real code the template parameters can be complex.

我当前的解决方法是使用可调用对象而不是自由函数。例如:

My current workaround is to use callable objects instead of free functions. For example:

class Foo
{
  public:
    template <class T> void operator()(T&&);
};

这可以正常工作,但是我敢肯定,这会使我的图书馆用户感到困惑。我可以使用一些模板魔术来使第一个版本正常工作吗?

This works fine, but I'm sure it will confuse users of my library. Is there some template magic I can use to make the first version work?

推荐答案


我可以使用模板魔术来使第一个版本正常工作吗?

Is there some template magic I can use to make the first version work?

我希望。我希望有一天。在这方面有一些建议(例如 P0119 P0834 )。在那之前,最好的办法是编写一个提升宏,以将您的 name 转换为调用该名称的函数对象:

I wish. And I hope someday. There have been several proposals in this area (e.g. P0119 and P0834). Until then, the best you can do is write a lifting macro to turn your name into a function object that calls that name:

#define FWD(...) std::forward<decltype(__VA_ARGS__)>(__VA_ARGS__)
#define LIFT(name) [&](auto&&... args)     \
    noexcept(noexcept(name(FWD(args)...))) \
    -> decltype(name(FWD(args)...))        \
    { return name(FWD(args)...); }

这可以让您编写:

CallMe(LIFT(Foo));

这可以满足您的要求。

这篇关于C ++中有什么方法可以在不调用函数模板或不提供其模板参数的情况下引用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆