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

标签 c++ templates c++11 typedef extern

typedef有两种情况当谈到 extern template declaration 时让我感到困惑和 explicit 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>;

为什么 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?

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

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

最佳答案

template class int_example;

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

14.7.2 Explicit instantiation

2 The syntax for explicit instantiation is:

explicit-instantiation:
externopt template declaration

There are two forms of explicit instantiation: an explicit instantiation definition and an explicit instantiation declaration. An explicit instantiation declaration begins with the extern keyword.

3 If the explicit instantiation is for a class or member class, the elaborated-type-specifier in the declaration shall include a simple-template-id.

simple-template-idA.12 模板 部分定义为:

simple-template-id:
template-name < template-argument-listopt >

int_example不符合simple-template-id的条件。
example<int>确实有资格作为 simple-template-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

关于c++ - 在模板实例化和外部模板声明中使用 typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34506356/

相关文章:

c++ - C/C++指针问题

c++ - 比较 C++ 中的结构

java - 如何对 jxls 模板中的非连续单元格求和

c++ - 如何根据模板中的类型编译函数?

C++11 自动和函数返回类型

c++ - 尝试从 Visual Studio 命令提示符调用 lib.exe

c++ - Bazel - 导入静态库时包括目录中的所有 header

php - 在 Codeigniter 中的所有 Controller 上具有固定 View

c++ - std::mutex::lock() 产生奇怪的(和不必要的)汇编代码

c++ - 如何解压可变参数模板,以便初始化相应的成员?