【问题标题】:How do I define a class template with specfic format of taking template arguments? e.g.: Fn(Args...)如何定义具有特定模板参数格式的类模板?例如:Fn(Args...)
【发布时间】:2020-12-17 20:44:33
【问题描述】:
template<class Fn, class ...Args>
class func_class<Fn(Args...)> // Do not know what to do here
{
        typedef typename result_of<Fn(Args...)>::type mytype;
        std::function<mytype(Args...)> func_;
        std::tuple<Args...> tuple1;
    public:
        func_class(Fn&& func_in, Args&& ...args) 
        {
            func_ = func_in;
            tuple1 = make_tuple(args...);
        }
    
        mytype
        exe () 
        {
            mytype ret;
            ret = apply(func_, tuple1);
            return ret;
        }
};

int func(int a) {return a;}

int main () {
   // return type of "func" can be deduced by "result_of<decltype(func)&(int)>::type"
   // And result_of is declared as "result_of<Fn(Args...)>"
   // Want func_class to have the same interface
   func_class<decltype(func)&(int)> fc; // Want to declare a object like this 
   fc.exe();
}

代码如上。 func 的返回类型可以由result_of&lt;decltype(func)&amp;(int)&gt;::type 推导出来。并且result_of 被声明为result_of&lt;Fn(Args...)&gt;。 想让func_class拥有和result_of一样的界面。
编译器抱怨如下:

test.cpp:211:7: error: 'func_class' is not a class template

我能做什么? 提前谢谢你。

【问题讨论】:

    标签: c++ class templates


    【解决方案1】:
    template<class Sig>
    struct bob;
    template<class R, class...Args>
    struct bob<R(Args...)>{
      //...
    };
    

    专业化。

    使用模式匹配失败的bob 会产生编译时错误。

    注意,当R 不是返回值并且Args...不是参数时使用R(Args...)语法会导致意外的怪癖,因为C/C++ 语言如何修改函数参数和返回值类型。

    这就是为什么 std::result_of&lt;F(Args...)&gt; 被弃用并被 std::invoke_result&lt;F, Args...&gt; 取代的原因。

    R(Args...)std::function 中使用得当,因为Args... 是函数参数,而Rfunction&lt;A(Args...)&gt;::operator() 的实际返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2016-12-27
      相关资源
      最近更新 更多