【问题标题】:Construct std::function with a constructor based on template使用基于模板的构造函数构造 std::function
【发布时间】:2012-09-12 11:03:04
【问题描述】:

是否可以使用模板参数定义的类型的构造函数构造std::function?

例如:

template <typename T>
bool registerType()
{
    const std::function<T()> func = &T::T; //I know this doesn't work
    //...
}

【问题讨论】:

    标签: c++ templates c++11 std-function


    【解决方案1】:

    我不这么认为,因为构造函数没有名称,你不能对它们进行指针/引用,而且通常它们的行为不像函数。

    您可以使用 lambda 来初始化具有相同签名的 std::function:

    const std::function<T()> func = [](void) { return T(); } // or something like that
    

    调用它会产生与使用表达式T() 构造T 类型的临时变量相同的结果,但可能具有不同的副作用。在真正的函数调用的情况下,return 语句中有一个额外的临时变量,名义上它被复制/移动到返回值。实现可能会也可能不会忽略额外的临时性。

    【讨论】:

      猜你喜欢
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      相关资源
      最近更新 更多