如何转发类模板的构造函数参数

P45*_*ent 1 c++ templates c++17

考虑一种默认值Bar

struct Bar
{
};
Run Code Online (Sandbox Code Playgroud)

以及 a 的特定情况BarMyBar它有一个需要 : 的构造函数int

struct MyBar
{
    MyBar(int n){}
};
Run Code Online (Sandbox Code Playgroud)

然后我有一个使用以下内容的类Bar

template<class ThisBar = Bar> struct Foo : ThisBar
{
    Foo(double){}; // Construct the 'Foo' from a 'double'
};
Run Code Online (Sandbox Code Playgroud)

但一个障碍是,如果我想要一个,Foo<MyBar>我需要能够构建MyBar

Foo<MyBar> f(1.0, 1);
Run Code Online (Sandbox Code Playgroud)

其中int用来构造MyBar。我的问题是如何编写这个构造函数,以便下面的代码可以在 C++17 中编译?

int main()
{
    Foo<MyBar> f(1.0, 1);
}
Run Code Online (Sandbox Code Playgroud)

Wei*_*hou 5

使用模板化构造函数并转发参数

template<class ThisBar = Bar> struct Foo : ThisBar
{
    double val;

    template <typename... Ts>
    Foo(double x, Ts&&... args): ThisBar{std::forward<Ts>(args)...}, val{x}{}
};
Run Code Online (Sandbox Code Playgroud)


joe*_*ech 5

您可以创建模板化构造函数并转发模板参数:

#include <utility>

struct Bar
{
};

struct MyBar
{
    MyBar(int n){}
};

template<class ThisBar = Bar> struct Foo : ThisBar
{
    template <typename... Ts>
    Foo(double, Ts&&... ts)
     : ThisBar(std::forward<Ts>(ts)...) 
    {};
};

int main()
{
    Foo<MyBar> f(1.0, 1);
}
Run Code Online (Sandbox Code Playgroud)

https://godbolt.org/z/WjfosqYqn