开发者

Template type constructor parameters

Given a template class:

template<class T>
class Foo
{
public:
    void FunctionThatCreatesT()
    {
        _object = new T;
    }
private:
    shared_ptr<T> _object;
}

Is it possible to somehow pass a set of constructor parameters for T to Foo (perhaps when Foo is constructed) such that Foo can use them when it creates T? A C++11 only solution is fine (so, variadics开发者_运维问答 are on the table for example).


Exactly that, variadic templates and perfect forwarding via std::forward.

#include <memory>
#include <utility>

template<class T>
class Foo
{
public:
    template<class... Args>
    void FunctionThatCreatesT(Args&&... args)
    {
        _object = new T(std::forward<Args>(args)...);
    }
private:
    std::shared_ptr<T> _object;
}

For a listing of how this works, see this excellent answer.

You can emulate a limited version of this in C++03 with many overloaded functions, but.. it's a PITA.

Also, this is only from memory, so no testing done. Might contain an off-by-one error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜