Construct std::function with a constructor based on template

泄露秘密 提交于 2019-12-18 08:25:54

问题


Is it possible to construct a std::function with the constructor of a type defined by a template argument?

For example:

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

回答1:


I don't think so, because constructors don't have names, you can't take a pointer/reference to them, and in general they don't behave quite like functions.

You could use a lambda to initialize a std::function with the same signature:

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

Calling it produces the same result as using the expression T() to construct a temporary of type T, but possibly with different side-effects. In the case of a true function call there's an extra temporary in the return statement, which nominally is copied/moved to the return value. The implementation may or may not elide the extra temporary.



来源:https://stackoverflow.com/questions/12386725/construct-stdfunction-with-a-constructor-based-on-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!