Ker*_* SB 4 c++ templates base-class name-lookup
在下面的设置中,我如何才能使它能够引用Bar
派生类中的名称Derived<T>
?
template <typename T> struct Foo
{
template <typename U> struct Bar { };
};
template <typename T> struct Derived : Foo<T>
{
// what goes here?
Bar<int> x; // Error: 'Bar' does not name a type
};
Run Code Online (Sandbox Code Playgroud)
我试过了using Foo<T>::Bar;
,但这没有用.是否有任何类型的using
声明可以使派生类知道嵌套基本模板的名称,以便我可以保持简单的声明Bar<int> x
?
我知道我可以说typename Foo<T>::template Bar<int> x;
,但我有很多这样的情况,我不想用这么多的冗长不必要地加重代码.我也有很多不同的" int
s",因此typedef
每个嵌套模板实例的a也是不可行的.
此外,我不能在此时使用GCC 4.7,也不能使用C++ 11,因此会喜欢没有模板别名的"传统"解决方案.
在C++ 11中,您可以使用别名模板:
template <typename T> struct Derived : Foo<T>
{
template<typename X> using Bar = typename Foo<T>::template Bar<X>;
Bar<int> x;
};
Run Code Online (Sandbox Code Playgroud)
编辑
传统的解决方案就是您已经说过的typename Foo<T>:template Bar<int>
,或模拟"模板类型定义"
template <typename T> struct Derived : Foo<T>
{
template<typename X>
struct Bar
{ typedef typename Foo<T>::template Bar<X> type; };
typename Bar<int>::type x;
};
Run Code Online (Sandbox Code Playgroud)
将别名模板添加到语言中的原因之一是它们支持在C++ 03中无法轻易表达的内容.