【问题标题】:Template specialization for all wide character types所有宽字符类型的模板特化
【发布时间】:2012-09-19 20:54:04
【问题描述】:

我现在想提高我在 C++ 模板方面的知识,但遇到了一个问题。是否可以编写一个模板函数来接受所有宽字符类型,如 std::wstring、wchar_t、wchar_t* 等?这是一个例子来说明我的意思:

template <typename T> Function(T1 var)
{
    // Do something with std::stringstream and the passed var;
}

上述函数的问题是它不适用于 wchar_t 或 std::wstring 例如。您需要改用 std::wstringstream 。我现在可以专注于:

template <> Function(wchar_t var)
{
    // Do something with std::wstringstream and the passed var;
}

现在我必须为每个宽字符串类型编写相同的函数,但是是否可以专门化一次并涵盖所有宽字符串类型?

提前谢谢!

【问题讨论】:

  • 当然,第一个函数适用于所有类型。问题是你没有显示代码,我猜你在那里声明了一些静态类型。向我们展示您想要的功能实现
  • 您可能只使用 std::basic_stringstream 与依赖于模板参数的模板参数。 std::stringstream 实际上是std::basic_stringstream&lt;char&gt;std::wstringstreamstd::basic_stringstream&lt;wchar_t&gt;
  • wchar_twchar_t* 是两个不同的东西。我不太确定你的函数应该做什么......
  • @KerrekSB:如果您将问题的主体想象为std::cout &lt;&lt; var;,那么这个问题是有道理的

标签: c++ templates


【解决方案1】:

使用特征技术。定义一些is_wide_char_type 类模板。像这样:

template <T>
struct is_wide_char_type { static const bool VALUE = false; };
template <>
struct is_wide_char_type<wchar_t> { static const bool VALUE = TRUE; };
... for others types the same.

然后将你的函数特化为两个版本,你需要定义类模板,因为函数模板不能部分特化:

template <typename T, boo isWideChar> class FunctionImpl;
template <typename T> struct FunctionImpl<T, false> {
  static void doIt() {
     // code for not wide char types
  }
};
template <typename T> struct FunctionImpl<T, true> {
  static void doIt() {
     // code for wide char types
  }
};


template <typename T> Function(T1 var)
{
   FunctionImpl<T, is_wide_char_type<T>::VALUE>::doIt();
}

或者考虑让它变得更简单,并包含在特征 is_wide_char_type&lt;T&gt; 中,而不仅仅是 T 的标签信息,还有关于使用哪个字符串流以及您喜欢的任何内容。

【讨论】:

  • 谢谢 PiotrNycz 这正是我想要的!有趣的是我几乎找到了你的解决方案,但我不知道函数不能部分专门化,我需要使用类来代替。谢谢!
  • 使用标签调度(参见boost.org/community/generic_programming.html#traits)只能通过重载函数来实现。我只是认为使用部分专用类的解决方案更容易,但请随意尝试标签调度。为此,您需要定义两个标记结构(每种一个)并在 is_Wide_char_type 中使用它。
  • 好的,我今天测试了你的解决方案,它工作正常。现在唯一的问题是 wchar_t 数组。例如,当我传递 wchar_t[3] 时,我必须强制转换为 wchar_t*,因为我找不到可变数组大小的 is_wide_char_type 版本。但其他一切正常。
  • 尝试显式模板参数:Function&lt;wchar_t[3]&gt;();。定义使用template &lt;size_t N&gt; struct is_wide_char_type&lt;wchar_t[N]&gt; { static const bool VALUE = TRUE; };。 AFAIK - 这应该工作。使用隐式模板参数 - 数组的指针解释总是会被选中 :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多