Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

c++ - Construct std::function with a constructor based on template

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
    //...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

1.4m articles

1.4m replys

5 comments

57.0k users

...