作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个像这样的模板函数:
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);
编译器无法编译它,因为它被假定为部分特化函数。
最佳答案
有一种方法可以使用 enable_if
魔法来重载(而不是专门化)foo
。
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;
};
关于templates - 模板返回值的模板函数的完全特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33969412/
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 4 年前。
正如您在 this travis.yml 中看到的那样文件,我的代码依赖于一些第三方库,我在构建项目之前将它们安装在远程系统上。 Travis 每次推送提交时都会下载并构建这些库,这可以避免吗?我的意
我是一名优秀的程序员,十分优秀!