【发布时间】:2017-04-28 11:43:13
【问题描述】:
我有一个函数“has_holes”,它会根据掩码计算一些东西。位数由“掩码”的类型决定。因此我想使用模板。此外,我只想允许 has_holes 的实例化,它按值获取参数。所以我添加了一个类型特征“remove_all_t”,它给出了基础类型。但是当我这样做时,我无法再构建它并得到错误:
“错误:没有匹配函数调用‘has_holes(unsigned int&)” 注意:候选模板被忽略:无法推断模板参数“BASE_TYPE”
但是,如果我明确地将功能实例化称为“has_holes”,它就可以工作。 我是否搞砸了模板实例化和类型推断规则?或者我的错误在哪里?
代码如下:
#include <iostream>
#include <limits>
#include <type_traits>
#include <experimental/type_traits>
//removes everything except arrays []
template<class T> struct remove_all { typedef T type; };
template<class T> struct remove_all<T*> : remove_all<T> {};
template<class T> struct remove_all<T&> : remove_all<T> {};
template<class T> struct remove_all<T&&> : remove_all<T> {};
template<class T> struct remove_all<T const> : remove_all<T> {};
template<class T> struct remove_all<T volatile> : remove_all<T> {};
template<class T> struct remove_all<T const volatile> : remove_all<T> {};
template<class T>
using remove_all_t = typename remove_all<T>::type;
template<typename BASE_TYPE, class = typename std::enable_if_t<std::experimental::is_unsigned_v<BASE_TYPE>, BASE_TYPE>>
bool has_holes(remove_all_t<BASE_TYPE> mask){ //remove "remove_all_t<>" and it will work
static_assert(std::numeric_limits<unsigned int>::max() > std::numeric_limits<decltype(mask) >::digits, "Base_type has to much digits max_digits=std::numeric_limits<unsigned int>::max()");
for (unsigned int pos{1}; pos<std::numeric_limits<decltype(mask)>::digits; ++pos ){
;//algorithm will be placed here, not implemented yet
}
return true;
}
int main()
{
unsigned int mask = 0b00110011;
auto result = has_holes<unsigned int>(mask); //works
auto result2 = has_holes(mask);//error: no matching function for call to 'has_holes(unsigned int&)'|
std::cout<<result<<" ..."<<result2<<std::endl;
return 0;
}
最好的问候, 亨德里克
【问题讨论】:
-
您的错误消息中应该包含更多内容,例如 candidate template denied: could't infer template argument 'BASE_TYPE'。编译器无法推断出你想要
BASE_TYPE是什么。 -
我将 gcc 与 Codeblocks 一起使用,其中没有显示完整的输出。我知道有一个选项可以启用 fullouput,但我还没有找到。
-
尝试使用 clang 编译会出现以下错误: //error: no matching function for call to 'has_holes(unsigned int&)'|注意:候选模板被忽略:无法推断模板参数“BASE_TYPE”
标签: c++ templates typetraits type-deduction