c++ - 模板类型构造函数参数

标签 c++ templates

给定一个模板类:

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

是否可以以某种方式将 T 的一组构造函数参数传递给 Foo(也许在构造 Foo 时),以便 Foo 在创建 T 时可以使用它们?仅限 C++11 的解决方案就可以了(例如,可变参数就在桌面上)。

最佳答案

正是如此,可变参数模板和通过 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;
}

有关其工作原理的列表,请参阅 this excellent answer .

您可以在 C++03 中使用许多重载函数来模拟此版本的有限版本,但是..它是一个 PITA。

此外,这只是凭内存,所以没有进行测试。可能包含相差一错误。

关于c++ - 模板类型构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7535546/

相关文章:

c++ - 类型别名和不完整的类型

c++ - 关于内存泄漏的问题

c++ - 强制 SFINAE 使用不同的返回类型

c++ - g++ 给 "unresolved overloaded function type"模板参数

php - Laravel 中的 "Use of undefined constant..."错误

c++ - 模板模板类中非类型参数的类型在 C++14 中不可推导,但在 C++17 中可推导

c++ - 32位和64位操作系统上的不同计算

c++ - C++ 中的运行时运算符

android - 压缩/解压缩内存中的数据

c++ - 返回指向函数静态数据的指针是否合适?