首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

模板特化中,怎么针对未定义的类型进行识别,与特化

2013-09-05 
模板特化中,如何针对未定义的类型进行识别,与特化?本帖最后由 laybor 于 2013-08-23 01:40:17 编辑如题。te

模板特化中,如何针对未定义的类型进行识别,与特化?
本帖最后由 laybor 于 2013-08-23 01:40:17 编辑 如题。



template<typename T>
struct node_t;

template<>
struct node_t<char>
{
enum {
value = 1,
};
};

namespace priv
{
template<typename T>
struct node_t
{
enum {
value = 2,
};
};

template <typename T>
struct get_t
{
enum {
value = node_t<T>::value
};
};
};

struct unknown_type{};


实际输出结果
priv::get_t<unknown_type>::value   =  2
priv::get_t<char>::value   =  2
与想象中的有出入,char的输出并不是前面所特化的1。被后面的通用特化给覆盖了。
我的理想输出是
priv::get_t<unknown_type>::value   =  2
priv::get_t<char>::value   =  1

并且,最外部空间的 node_t 必须保持是未定义类型,不能对其进行破坏
(因为需要未定义类型的error来进行代码错误定位)。
换句话说,就是在外部空间时,直接使用node_t<unknown_type>::value,会提示使用未定义类型,必须保持这个功能,让用户来编写特化代码。

主要目的是,当node_t<??>未被特化的情况下,某模板(比如priv::get_t),可以实现使用缺省的特化类型。
其实就是在不进行破坏的情况下,如何识别node_t<??> 是否被特化。

允许使用tr1的type_traits,不过我研究了下,好像没啥好的方法。


模板特化?未定义类型
[解决办法]

template<typename T>
struct node_t;

template<>
struct node_t<char>
{
enum {
value = 1,
};
};

namespace priv
{
template<typename T>
struct xnode_t : node_t<T>{};
template xnode_t<char>;
}

namespace priv
{
template<typename T>
struct node_t
{
enum {
value = 2,
};
};

template <typename T>
struct get_t : xnode_t<T>
{
};
};


[解决办法]
我觉得楼主的意思很明确,
::node_t<T> 有特化的话,get_t 就用 ::node_t<T>


没有特化的话,就用 priv::node_t<T>;
同时要保持 ::node_t 对于没有特化的类型为 incomplete type,引发编译错误。


template<typename T> struct node_t;

template <> struct node_t<char> { enum { value = 1 }; };

namespace priv
{
 template<typename T>
 class is_global_node_t
 {
  typedef char one;
  typedef struct { char arr[2]; } two;
  template<typename U>
  static decltype(::node_t<U>::value, one()) test(int);
  template<typename> static two test (...);
 public:
  static constexpr bool value = sizeof(test<T>(0)) == 1;
 };

 template <typename T>
 struct node_t { enum { value = 2 }; };

 template <typename T, bool = is_global_node_t<T>::value>
 struct get_t : ::node_t<T> { };

 template <typename T>
 struct get_t<T,false> : node_t<T> { };
};

struct unknown_type { };
// open the following will print 3.
// template <> struct node_t<unknown_type> { enum { value = 3 }; };

#include <iostream>
int main ()
{
 std::cout <<  priv::get_t<char>::value << std::endl; // 1
 std::cout <<  priv::get_t<unknown_type>::value << std::endl; // 2
}

热点排行