c++ - 将别名模板传递给它所依赖的模板的基类

标签 c++ c++11 templates

考虑以下代码,它定义了要作为模板模板参数传递的别名模板:

template<template<class T> class SomeFoo>
class Base {};

template<class T, class Bar>
class Foo {};

class Bar;

template<class T>
using BarFoo = Foo<T, Bar>;

class Bar : public Base<BarFoo> {};

这按预期工作。但是,如果 Bar 本身是一个模板,则此解决方案是不可能的,因为别名模板取决于 Bar 的具体实例化。在 Bar 内部定义别名模板也没有帮助,因为在给出基类时它还不可用。由于似乎不可能在参数列表中“即时”定义别名模板,因此我能想到的唯一解决方法是将 Bar 传递给 Base 并在那里定义别名模板:

template<template<class T, class Derived> class SomeFooTL, class Derived>
class Base
{
    template<class T>
    using SomeFoo = SomeFooTL<T, Derived>;
};

template<class T, class Bar>
class Foo {};

template<class S>
class Bar : public Base<Foo, Bar<S>> {};

然而,这非常令人不满意,因为可能(并且确实)有其他 Foo 不依赖于除 T 之外的任何东西,而现在被迫采用不必要的第二个模板参数。

有谁知道更好的方法来实现这一目标吗?

最佳答案

如果我正确理解你想要什么,你需要一个帮助者,并使用不明显的语法:

template<template<class> class>
class Base {};

template<class, class>
class Foo {};

template <typename> class Bar;

template <typename S> struct UsingHelper {
    template <typename T>
    using BarFoo = Foo<T, Bar<S>>;
};

template <typename S>
class Bar : public Base<UsingHelper<S>::template BarFoo> {};

template UsingHelper<S>::template BarFoo 中需要因为它是一个依赖上下文,并且它会被“解释”为值,而不是没有。 (它类似于 typename my_class<T>::type ,但 BarFoo 是一个模板,而不是类型。)

关于c++ - 将别名模板传递给它所依赖的模板的基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46689489/

相关文章:

c++ - 为什么基类的构造方法被调用了两次?

c++ - 模板与类型转换

JavaScript 模板

c++ - C 中的函数指针 - 地址运算符 "unnecessary"

c++ - 错误 : assignment of member ‘x::x’ in read-only object

c++ - void 指针可以指向 lambda 函数吗?

c++ - 使用以下 has_member 函数时 SFINAE 无法正常工作的原因是什么?

c++ - C++模板短路逻辑AND(&&)

c++ - 是否可以将 C++ UWP 应用程序链接到 Mysql 数据库?

c++ - 在 C++ 中使用 decltype()、auto 或 RTTI 进行类型相等性测试? Boost 有这个功能吗?