【问题标题】:Full specializtion of a template function for a template return value模板返回值的模板函数的完全专业化
【发布时间】:2015-11-28 08:47:06
【问题描述】:

假设我有一个这样的模板函数:

template <typename Key>
Key foo(const string &name);

我知道要专门化一个模板函数,我们必须像这样完全专门化它:

template<>
int foo<int>(const string &name);

但现在我正在寻找一种方法来将此函数专门用于模板对象,如下所示:

template<>
Bar<Key> foo<Bar<Key>>(const string &name);

我认为这不会违反任何 c++11 专门化和函数覆盖的法律。但我仍然找不到这样做的方法。

我更喜欢不使用类,而是使用能够进行部分专业化来实现此功能的函数。你有什么建议来实现这个函数并将它专门用于模板返回值?

编辑:

我提到的作为特化示例的函数没有有效的语法,因为它具有未定义的类型Key。我只是写它以表明没有可能的解决方案。如果我尝试将其完全定义为:

template<typename Key>
Bar<Key> foo<Bar<Key>>(const string &name);

编译器无法编译它,因为它被假定为偏特化函数。

【问题讨论】:

  • 为什么要专业化?不能超载吗?
  • 所有函数的输入参数都相同。我怎样才能超载它?
  • 您到底遇到了什么类型的错误?
  • 我不认为foo&lt;Bar&lt;Key&gt;&gt; 是一个完整的专业。 Key 是非模板类吗?
  • 我写的代码是错误的,因为Key没有定义。这只是一个例子,表明这是不可能的。如果我使用这样的东西:template&lt;typename Key&gt; Bar&lt;Key&gt; foo&lt;Bar&lt;Key&gt;&gt; (const string &amp;name);g++ 告诉我function template partial specialization foo&lt;Bar&lt;Key&gt;&gt; is not allowed

标签: templates c++11


【解决方案1】:

有一种方法可以重载(而不是专门化)fooenable_if 魔法。

template <typename Key>
typename std::enable_if<!is_specializaton<Bar, Key>::value, Key>::type
foo(const string &name);

template<typename KeyCont>
typename std::enable_if<is_specializaton<Bar, KeyCont>::value, KeyCont>::type
foo(const string &name);

is_specialization 可以这样定义:

template <template<typename...> class T, typename ... args>
struct is_specializaton {
    static const bool value = false;
};

template <template<typename ... > class a, typename ... args >
struct is_specializaton<a, a<args...>> {
    static const bool value = true;
};

【讨论】:

  • 效果很好。这是一个很好的解决方案,但我对其进行了一些更改,我使用了一个模板类 is_bar&lt;typename Key&gt;,它表明这是否是一个 bar 类,因为我对此函数有另一个专业化,我认为这种方式更容易。
猜你喜欢
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2011-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多