使用可变参数模板进行函数调用的模板类型推导

时间:2019-02-21 00:15:40

标签: c++ templates visual-c++ variadic-templates template-deduction

我正在使用VC ++ /std:c++latest,我想确定作为模板参数传递给结构的成员函数的RET-Type,Class-Type和参数类型。 我找到了一种方法:

template <auto MEMBER>
class C;
template <class RET, class T, class... ARGS, RET(T::*MEMBER)(ARGS...)>
class C<MEMBER>
{
public:
    template <class... ARGS2>
    RET operator()(ARGS2&&... args)
    {
        // place holder
        (reinterpret_cast<T*>(0)->*MEMBER)(std::forward<ARGS2>(args)...);
    }
};
struct A
{
    void f(int, int) {}
};
int main()
{
    C<&A::f> c; // error C2079: 'instance' uses undefined class 'C'
    c(5, 5);
}

但是此解决方案仅适用于g ++。

所以

  1. 这是VC ++中的错误吗?
  2. 还有另一种方法可以实现同一目标吗?

2 个答案:

答案 0 :(得分:2)

不是答案(对不起),而是长篇评论:如果您想要完美的转发,则需要模板函数/方法中的通用引用

我的意思是...我建议按照以下方式或类似方式重写operator()(我还为T对象添加了完美的转发方式)

template <typename U, typename ... As>
RET operator()(U && u, As && ... args)
{
    (std::forward<U>(u).*MEMBER)(std::forward<As>(args)...);
}

因此您可以编写(至少使用g ++和clang ++)

A  a;
C<&A::f> c;
c(a, 5, 5);

答案 1 :(得分:0)

@ max66的提示让我弄清楚,我不需要推断函数的参数,从而可以轻松推断出返回类型和类类型。

valueAxis.renderer.inversed = true;

编辑:针对Visual Studio 2019的错误已修复:https://developercommunity.visualstudio.com/content/problem/464355/error-c2079-instance-uses-undefined-class-c.html