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

时间:2015-12-29 07:21:34

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

typedefextern 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 那样。< / p>

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

1 个答案:

答案 0 :(得分:2)

template class int_example;

不合法。来自C ++ 11 Stanard:

  

14.7.2明确的实例化

     

2显式实例化的语法是:

     

显式实例:
  extern opt template 声明

     

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

     

3如果显式实例化是针对类或成员类的,声明中的 elaborated-type-specifier 应包含 simple-template-id

simple-template-id A.12模板部分中定义为:

  

简单模板id
   template-name < template-argument-list opt >

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
相关问题