考虑以下代码,它定义了要作为模板模板参数传递的别名模板:
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/