C++11:无法推断模板参数
C++11: Unable to infer template argument
>行:
auto test = add<Suc < Suc < Suc < Suc < Zero > > > > > (three, one);
如果我替换为:
auto test = add(three, one);
我忽略了错误的候选模板:无法使用 std=c++11 的 Clang 编译器推断模板参数"W" 我无法想象任何其他值满足 W 对于它,有没有办法修复它?
#include <type_traits>
template<typename T>
class Nat {
};
class Zero : public Nat<Zero> {
};
template<typename T,
typename std::enable_if<std::is_base_of<Nat<T>, T>::value>::type* = nullptr>
class Suc : public Nat<Suc<T> > {
public:
T val;
explicit Suc(T v): val(v) {}
};
template<typename T>
Suc<T> suc(T val) {
Suc<T> next(val);
return next;
}
template<typename W, typename U, typename V,
typename std::enable_if<std::is_base_of<Nat<W>, W>::value>::type* = nullptr,
typename std::enable_if<std::is_base_of<Nat<U>, U>::value>::type* = nullptr,
typename std::enable_if<std::is_base_of<Nat<V>, V>::value>::type* = nullptr
>
W add(Suc<U> m, V n) {
Suc<V> next (n);
return add<W>(m.val, next);
}
template<typename V>
V add(Zero m, V n) {
return n;
}
int main() {
Zero zero;
auto one = suc(zero);
auto two = suc(one);
auto three = suc(two);
auto four = suc(three);
auto test = add<Suc < Suc < Suc < Suc < Zero > > > > > (three, one);
return 0;
}
控制台输出:
c++ -std=c++11 main.cc
main.cc:48:17: error: no matching function
for call to 'add'
auto test = add(three, one);
^~~
main.cc:35:3: note: candidate function
template not viable: no known
conversion from 'Suc<Suc<Suc<Zero,
nullptr>, nullptr>, nullptr>' to
'Zero' for 1st argument
V add(Zero m, V n) {
^
main.cc:29:3: note: candidate template
ignored: couldn't infer template
argument 'W'
W add(Suc<U> m, V n) {
^
1 error generated.
此错误消息告诉您原因:
主.cc:29:3:注意:候选模板 已忽略:无法推断模板 参数"W">
返回类型是模板参数,但编译器无法从函数参数推断返回类型,您必须指定它。
但是,decltype
可以帮助您计算返回类型应该是什么:
template<typename U, typename V>
auto add(Suc<U> m, V n) -> decltype(add(m.val, Suc<V>(n))) {
Suc<V> next (n);
return add(m.val, next);
}
相关文章:
- 在 c++11 中为 pthread 设置调度参数
- 为什么 c++11 std::lock 和 std::scoped_lock 至少需要 2 个参数?
- 在 C++11 中获取函子作为参数
- C++/11 auto 关键字是在更有效时推导参数进行按引用传递,还是始终按值传递?
- 如何捕获函数参数并存储函数指针以供以后在 C++11 中执行?
- C++11:无法推断模板参数
- 带有void类型和参数的C++11模板专用化
- 使用 C++11 将指向成员函数的指针作为参数传递
- 遍历地图并将该对用作参考参数 C++11
- 发生 Qt5.11 应用插件构建错误:信号和插槽参数不兼容
- 将方法作为模板化参数传递 C++11
- C++11:标准::result_of<>模板参数与标准::函数<>
- 如果没有带有函数签名的 rvalue 参数,是否会执行 C++ 11 中的移动语义?
- C++11: 如何编写一个像 Get 一样工作的模板函数<tuple>...但是收到参数包?
- 如何在 C++11 中创建具有命令行参数大小的动态数组?
- C++ 11 个模板,参数包的别名
- 谷物/C++ 11 - 如何指定反序列化的可选参数
- 变量作为 C++11 属性参数
- 具有列表参数C++11/C++14样式的求和函数
- 将 lambda 表达式传递给 lambda 参数 c++11