在模板实例化和extern模板声明中使用typedef

using typedef in template instantiation and extern template declaration

本文关键字:typedef extern 实例化 声明      更新时间:2023-10-16

当谈到extern template declarationexplicit template instantiation时,typedef有两种情况让我感到困惑。

要说明这两者,请参阅下面的2个示例代码片段。

考虑以下示例(案例1)

// suppose following code in some cpp file    
template <typename T>
    struct example
{
    T value;
};
// valid typedefs
typedef example<int> int_example;
typedef example<std::string> string_example;
// explicit instantiation using above typedefs
template class int_example; // -> compile time error
template class string_example; // -> compile time error
// instead we need to use type names
template class example<int>; // -> OK
template class example<std::string>; // -> OK
// QUESTION 1: Why does this work however? is this valid code?
typedef std::string type_string;
template class example<type_string>;

为什么template class example<type_string>可以使用typedef?为什么CCD_ 5无效?

考虑以下示例(案例2)

// suppose following code is in some header file
template <typename T>
struct example
{
    T value;
};
// valid typedefs
typedef std::string type_string;
typedef example<type_string> string_example;
// Explicit instantiation declaration
// QUESTION 2: Is this valid code? if not why not?
extern template string_example; // -> at least this compiles, but is it OK?

正如上面的评论中所质疑的那样,在extern template declaration中使用typedef是否有效,就像上面的例子一样,以及为什么它的编译与Case1不同。

我读过类似的案例,但没有一个能给出以上两个问题的详细答案。非常感谢详细的阐述!

template class int_example;

不合法。来自C++11标准:

14.7.2显式实例化

2显式实例化的语法是:

显式实例化:
externopttemplate声明

显式实例化有两种形式:显式实例化定义和显式实例化声明。显式实例化声明以extern关键字开头。

3如果显式实例化是针对类或成员类的,则声明中的详细说明的类型说明符应包括simple-template-id

简单模板id在第A.12节模板中定义为:

简单模板id:
模板名称<模板参数列表opt>

int_example不符合简单模板id的条件
example<int>确实符合简单模板id的条件。

然而,按照这个逻辑,

extern template string_example;

也不合法。我不知道这对你来说是怎么回事。当我试图在g++4.9.3中编译这样一行时,我得到了以下错误。

socc.cc:15:31: error: expected unqualified-id before ‘;’ token
 extern template string_example; // -> compile time error