在模板实例化和extern模板声明中使用typedef
using typedef in template instantiation and extern template declaration
当谈到extern template declaration
和explicit 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显式实例化的语法是:
显式实例化:
extern
opttemplate
声明显式实例化有两种形式:显式实例化定义和显式实例化声明。显式实例化声明以
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
相关文章:
- C++:TypeDef使用元组
- Visual Studio 2015:Extern "C" 和 "export" 关键字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 如何使用extern类
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 为什么在使用typedef时类推导指南会失败
- 自动重复 extern "C"函数中的类构造函数采用的相同参数
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 尝试根据类中 typedef 的存在来专门化模板函数
- 如何重新定义MPI_FLOAT,MPI_DOUBLE以 typedef 的方式
- typedef 枚举和枚举类有什么区别?
- 使用说明符 extern 声明的C++中的标识符链接
- 在类模板中使用 typedef 时出错
- 模板类中的 typedef 语句
- 在 typedef 内部使用 const 关键字和在 typedef 外部使用 const 关键字之间有区别吗?
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 可视化编译与 C++ 中的 Extern 变量
- 是否可以在不使用 decltype 的情况下推断先前定义的 extern 变量的类型
- 如何使用默认值将枚举声明为 extern
- 在模板实例化和extern模板声明中使用typedef