cod*_*ddy 5 c++ templates typedef extern c++11
有两种情况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>;
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个问题的详细答案.详细的阐述非常感谢!
template class int_example;\nRun Code Online (Sandbox Code Playgroud)\n不合法。来自 C++11 标准:
\n\n\n14.7.2 显式实例化
\n2 显式实例化的语法为:
\n显式实例化:
\n
\nexternopttemplate声明显式实例化有两种形式:显式实例化定义和显式实例化声明。显式实例化声明以
\nextern关键字开头。3 如果显式实例化是针对类或成员类,则声明中的详细类型说明符应包含简单模板 ID。
\n
simple-template-id在A.12节模板中定义为:
\n\n\n简单模板 ID:
\n
\n模板名称<模板参数列表opt>
int_example不符合simple-template-id 的资格。
\nexample<int>确实有资格作为simple-template-id。
然而,按照这个逻辑,
\nextern template string_example;\nRun Code Online (Sandbox Code Playgroud)\n也不合法。我不知道它对你有什么作用。当我尝试在 g++ 4.9.3 中编译这样的行时,出现以下错误。
\ntemplate class int_example;\nRun Code Online (Sandbox Code Playgroud)\n