c++ - 模板模板参数用作其他参数的默认值

标签 c++ templates

我正在尝试使用模板模板参数作为其他模板参数的默认值,但是当我尝试使用标识符(模板模板参数名称/id)时找不到它。 我正在使用 VS 2013。 我的想法是,我有一个基于特定类型模板实例化的“工厂”类,我需要返回另一个具有相同数量参数 (4) 但具有相同特化的对象。

template<class T1, class T2,class T3, class T4>
class CommandBus
{...}

template <
template<class T1, class T2, class T3, class T4> class ListenerType,
//The Line bellow fails to compile, T1 is not visible
//E0020 identifier "T1" is undefine 
class CommandBusType = CommandBus<T1, T2, T3, T4> >
class CommandBusFactory {
static auto Get() {
        return CommandBusType{};
    }
};

int main{
//Say I would Have some Object :
Listener<int, int ,int int> Listener;
//Withought the Factory I would have to manually generate a ComamndBus of the same specialization (int , int , int, int):
CommandBus<int,int,int,int> cmdBus;


//But I could use a factory, things should look like:
Listener<int, int ,int int> listener;
auto cmdBus = CommandBusFactory<Listener<int,int,int,int>>::Get();
}

我原以为这会起作用,但编译器提示说,例如 未找到模板参数 CommandBusType 的默认值 (CommandBus) 的标识符 T1、T2 等

是否可以使用模板模板参数作为其他模板参数的默认值?

最佳答案

CommandBusFactory的第一个模板参数本身就是一个模板。

然而,在 main你通过了Listener<int,int,int,int>对它来说,这不是模板,而是类型。您需要一个类型模板参数。

然后,要从该类型中提取模板参数,您可以使用模板特化:

template
<
    class X,
    template <class, class, class, class> class Y
>
struct copy_template_params;

template
<
    template <class, class, class, class> class X,
    class A, class B, class C, class D,
    template <class, class, class, class> class Y
>
struct copy_template_params<X<A,B,C,D>,Y>
{
    using type = Y<A,B,C,D>;
};

template
<
    class ListenerType, 
    class CommandBusType = typename copy_template_params<ListenerType,CommandBus>::type
>
class CommandBusFactory
{
  public:
    static auto Get()
    {
        return CommandBusType{};
    }
};

关于c++ - 模板模板参数用作其他参数的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56128523/

相关文章:

c++ - 如何使用可变模板参数保存可变数量的参数?

c++ - 以泛型函数为参数的泛型函数

c++ - 将 std::forward 作为默认参数传递?

java - 编译时变量的名称和生命周期

c++ - std::shared_ptr:未调用自定义删除器

c# - 从模板类转换

c++ - 在 std::function 中使用模板参数

c++ - 将 char 指针传递给接受对 char 数组的引用的函数

c++ - 使用 Win32 子类化现有窗口

c++ - 指向二维数组的指针在 C++ 中如何工作?