2017-10-11 45 views
2

考虑下面的代码模板,定义了一个别名模板来作为模板的模板参数进行传递:传递别名模板基类这取决于

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中定义别名模板也没有帮助,因为在给出基类时它还不可用。因为它似乎没有可以定义“对飞”在参数列表中的别名模板,唯一的工作,我身边能想出是通过BarBase和定义别名模板有:

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之外不依赖任何东西,现在被迫采取不必要的第二模板参数。

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

+0

不知道我明白了,但是不能通过一个你有模板的类<...> using type = ...;而不是传递一个模板? – lorro

+0

@lorro我想我明白你在做什么,我不得不认为通过...(顺便提一下,关于这个问题有什么不清楚的地方?也许我可以重新翻译它。)编辑:是的,我认为这应该工作!让它成为正确的答案,我会接受它。 – Knoep

回答

2

如果我理解正确的话,你想要什么,你需要一个帮手,并使用没有明显的语法:

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是一个模板,而不是一个类型。)

+0

这很好地解决了它!它比在helper类中传递模板模板参数更清洁,因为它不污染基类。通过让UsingHelper直接将Bar作为模板参数并从而摆脱前向声明,可以使其更短。 – Knoep

0

相反的:

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

你可能想:

template<class SomeFooT> 
class Base {}; 

并使用SomeFooT::type<T>作为模板:

struct BarFooT { 
    template<typename T> 
    using type = ...; 
}; 

然后你就可以预先声明struct BarFooT;

+0

您能否更具体地向前宣布BarFooT的帮助? (或者我在这里错过了什么?) – Knoep