【发布时间】: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<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 个问题的详细答案。非常感谢详细的阐述!
【问题讨论】:
标签: c++ templates c++11 typedef extern