首页 > 解决方案 > 模板模板参数是否在模板参数声明中创建“内部范围”?

问题描述

美好的一天 StackOverflow!

我正在学习 C++,现在我专注于模板。

我正在阅读 C++ 模板:完整指南第 2 版。

我在第 12 章,特别是 12.2.3,关于模板模板参数。

根据我的理解和各种测试,它似乎像块作用域一样工作,外部作用域无法访问内部作用域声明。

那是对的吗?

这是一个例子:

// T is declared inside the "global scope",
// so it can be used inside the struct
template<class T, class Alloc> struct _
{
   T t;
};

template< template<class T, class Alloc> class Container >
struct _
{
   Container c; // error, Container is a template class,
                // so it needs 2 more parameters
   T t; // T is declared inside the 'Container' scope,
        // so it can't be used inside the structure
};

template< // global scope
    template<
        template< class T, class Alloc = MyAlloc > class C // inner-inner scope
        , class Alloc = MyAlloc > class D // inner scope, can't access T
        , class Alloc = MyAlloc > class E // global, can't access T nor C
>
struct _
{
    E<D<C<T>>> e; // E< D< C<T, MyAlloc>, MyAlloc>, MyAlloc>
};

template<template<class T> class STL_Container>,
         class U = T // error, T is not declared inside this scope
>
struct _;

template< template<class T> class STL_Container,
         class T,
         class U = T // references the "global" T,
                     // not the one declared inside the container
>
struct _;

非常感谢您的宝贵时间。

标签: c++templateslanguage-lawyerc++17

解决方案


推荐阅读