c++ - 为什么我不能推断出类模板参数之一?
问题描述
我这里有一些代码
template<typename T, std::size_t size, typename funcType>
struct foo
{
public:
foo(const funcType& func) : m_func(func) {}
~foo() {}
void m_call() { m_func(); }
private:
const funcType& m_func;
T x[size];
};
void printString() { std::cout << "some string\n"; }
我可以创建一个对象
foo<int, 3, void(*)()> someObject(printString);
或者
foo<int, 3, decltype(printString)> someObject(printString);
但是当我尝试这样做时:
foo<int, 3> someObject(printString);
我在 g++ 10.2 上收到此错误
error: wrong number of template arguments (2, should be 3)
foo<int, 3> someObject(printString);
^
note: provided for 'template<class T, long unsigned int size, class funcType> struct foo'
struct foo
为什么我不能这样做?编译器不知道是什么类型printString
吗?
如果我foo
改变
template<typename funcType>
struct foo
{
public:
foo(const funcType& func) : m_func(func) {}
~foo() {}
void m_call() { m_func(); }
private:
const funcType& m_func;
};
我可以正常创建
foo someObject(printString);
我错过了什么吗?
解决方案
使用模板函数创建对象并从函数调用中扣除缺少的模板参数。像这样的东西。
template<typename T, std::size_t Size, typename FunctionT>
foo<T, Size, FunctionT> create_foo(const FunctionT &func) {
return foo<T, Size, FunctionT>(func);
}
auto foo_obj = create_foo<int, 3>(printString);
推荐阅读
- javascript - 正则表达式不允许开头和结尾的空格
- java - 如何从非活动类中删除 FusedlocationProviderClient 位置更新
- vaadin - 3.0.0.beta 的 Vaadin 上下文菜单添加错误,但适用于 2.1.0
- c# - 为什么这个递归搜索返回不相关的结果?
- c++ - 在 QT 中的两个窗口之间共享 websocket 连接
- javascript - 我可以将 Dart 编译的 JS (JavaScript) 用于静态网站的 Firebase 托管吗
- javafx-css - Javafx CSS:用 CSS 绘制文本
- javascript - 我应该预先分配一个数组还是随我增长
- python - 对数据框中的下 i 行使用 Python 循环
- objective-c - 如何操作 ios 代码