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

cod*_*ddy 5 c++ templates typedef extern c++11

有两种情况typedef混淆了我,当谈到extern template declarationexplicit template instantiation.

为了说明这两个,请参见下面的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>;
Run Code Online (Sandbox Code Playgroud)

为什么template class example<type_string>使用typedef?为什么它有效而template class string_example不是?

考虑以下示例(案例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?
Run Code Online (Sandbox Code Playgroud)

正如上面的评论中所提到的那样,使用typedef是否有效extern template declaration,就像上面的例子一样,为什么这个编译不像Case1那样,它没有.

我已经阅读了类似的案例,但没有一个给出上述2个问题的详细答案.详细的阐述非常感谢!

R S*_*ahu 3

template class int_example;\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
\n

14.7.2 显式实例化

\n

2 显式实例化的语法为:

\n

显式实例化:
\n externopt template 声明

\n

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

\n

3 如果显式实例化是针对类或成员类,则声明中的详细类型说明符应包含简单模板 ID。

\n
\n

simple-template-id在A.12节模板中定义为:

\n
\n

简单模板 ID:
\n模板名称 < 模板参数列表opt >

\n
\n

int_example不符合simple-template-id 的资格。
\nexample<int>确实有资格作为simple-template-id

\n

然而,按照这个逻辑,

\n
extern template string_example;\n
Run Code Online (Sandbox Code Playgroud)\n

也不合法。我不知道它对你有什么作用。当我尝试在 g++ 4.9.3 中编译这样的行时,出现以下错误。

\n
template class int_example;\n
Run Code Online (Sandbox Code Playgroud)\n