使用基于模板的构造函数构造std :: function

Gra*_*eme 5 c++ templates c++11 std-function

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

例如:

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

Ste*_*sop 10

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

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

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

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