【问题标题】:using typedef in template instantiation and extern template declaration在模板实例化和外部模板声明中使用 typedef
【发布时间】:2015-12-29 07:21:33
【问题描述】:

当谈到extern template declaration 和explicit template instantiation 时,typedef 有两种情况让我感到困惑。

为了说明这两者,请参见下面的 2 个示例代码 sn-ps。

考虑以下示例(案例 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&lt;type_string&gt; 与 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 个问题的详细答案。非常感谢详细的阐述!

【问题讨论】:

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


    【解决方案1】:
    template class int_example;
    

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

    14.7.2 显式实例化

    2 显式实例化的语法是:

    显式实例化:
    externopttemplate 声明

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

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

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

    simple-template-id:
    template-name &lt; template-argument-listopt子>&gt;

    int_example 不符合simple-template-id。
    example&lt;int&gt; 符合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
    

    【讨论】:

    • 你知道为什么 template class example&lt;type_string&gt;; 和 extern template class example&lt;type_string&gt;; 有效(或者它不与 GCC 一起使用)吗?我使用的是 MSVC-140 btw 并且它有效。非常感谢!
    • example&lt;type_string&gt; 有资格作为 simple-template-id。
    • 谢谢,我已经用 GCC 做了一些测试,在某些情况下 g++ 会为 example&lt;type_string&gt; 等情况发出未定义的引用,但 msvc 编译得很好,也有一些情况下 msvc 会发出警告但没有g++,显然这种情况既没有被标准描述也没有很好地定义。
    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多