【发布时间】: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<Bar<Key>>是一个完整的专业。Key是非模板类吗? -
我写的代码是错误的,因为
Key没有定义。这只是一个例子,表明这是不可能的。如果我使用这样的东西:template<typename Key> Bar<Key> foo<Bar<Key>> (const string &name);g++ 告诉我function template partial specialization foo<Bar<Key>> is not allowed