【问题标题】:Can forward declared type templates participate in template specialization ?前向声明的类型模板可以参与模板特化吗?
【发布时间】:2015-05-26 14:49:13
【问题描述】:

以下不编译

#include <iostream>
#include <type_traits>

// forward declaration of a type template
template<class T, class Alloc = std::allocator<T>> class std::vector; 

template<class T>
struct is_vector : std::false_type { };

// using the forward declared type template
template<class T, class Alloc>
struct is_vector<std::vector<T, Alloc>> : std::true_type { };


#include <vector>

int main()
{
    std::cout << is_vector<std::vector<int>>::value << std::endl;
}

我想确保前向声明的类型模板(在vector 之上)在专业化上下文中实际上是不可用的,并且这不是一个错误的实现。另外为什么会发生这种情况?我不想创建vector&lt;&gt; 类型的对象,仅将其用作在专业之间分派的标签; 在实例化点包含&lt;vector&gt; 不够(is_vector&lt;&gt; 的调用站点)

【问题讨论】:

  • 你的前向声明是错误的。

标签: c++ templates template-meta-programming


【解决方案1】:

标准库容器is undefined behavior 的前向声明(如果您设法编译它),因此对于std::vector,您必须在定义is_vector 之前#include &lt;vector&gt;

对于您自己的类型,您可以这样做:

// forward declaration of a type template
namespace my {
    template<class T, class Alloc> class vector; 
}

template<class T>
struct is_vector : std::false_type { };

// using the forward declared type template
template<class T, class Alloc>
struct is_vector<my::vector<T, Alloc>> : std::true_type { };

namespace my {
    template<class T, class Alloc = std::allocator<T>> class vector {}; 
}

【讨论】:

  • 我得到了要在 VS2012 中编译的代码的变体(它在 gcc 中失败),所以对整个情况感到困惑。谢谢你的信息
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
相关资源
最近更新 更多