【发布时间】:2021-09-16 20:08:37
【问题描述】:
我开始使用模板,并试图找出以下不起作用的原因。
class testclass1
{
public:
template <typename...Ts>
using TFunc = std::function<void(Ts*...)>;
template <typename...Ts>
void SetFunction(TFunc<Ts...> tf)
{
// Do something
}
};
template<typename...Ts>
class testclass2
{
public:
using TFunc = std::function<void(Ts*...)>;
void SetFunction(TFunc tf)
{
// Do something
}
};
void some_function(std::string*, double*)
{
}
int main()
{
testclass1 tc1;
testclass2<std::string, double> tc2;
testclass1::TFunc<std::string, double> tf1 = some_function;
tc1.SetFunction<std::string, double>(tf1);
tc1.SetFunction<std::string, double>(testclass1::TFunc<std::string, double>{tf1});
tc2.SetFunction(some_function);
tc1.SetFunction<std::string, double>(some_function);
}
除了最后一个版本,一切正常
tc1.SetFunction<std::string, double>(some_function);
这实际上是我想做的,因为它的样板要少得多,而且我不希望 testclass1 需要模板参数。
最后一行给出如下编译错误:
没有匹配的成员函数调用“SetFunction”
- 候选模板被忽略:无法匹配 'function
...)>' 与 'void ()(std::__1::basic_string *, double *)'
我不明白附加的“type-parameter-0-0”是什么。直观地说,这看起来很像链接到隐式 *this 指针的问题,但我不明白为什么 TFunc 会是成员函数并具有隐式 *this 指针(或者 this 是否链接到 std::function?)。此外,将代码 template <typename...Ts> using TFunc = std::function<void(Ts*...)>; 移出 testclass1 不会改变任何内容。
通过浏览不同的相关问答,您似乎不能将 std::function 与模板函数一起使用。这是这里的问题吗?
有没有办法让tc1.SetFunction<std::string, double>(some_function);在 testclass1 中工作?
提前致谢。
更新:我正在尝试解释解释,我想我有点明白了,但后来——想一想——我仍然不是 100% 确定。考虑以下代码:
template <typename...Ts>
using test_tuple = std::tuple<Ts...>;
template <typename...Ts>
void test_func(test_tuple<Ts...> tup)
{
// Do something
// e.g., PrintTuple(tup);
}
int main()
{
test_tuple<std::string, double> tt{"Hi", 3.1459f};
test_func<std::string>(tt);
}
在这种情况下,参数包中只指定了std::string,并推导出了双精度数(因此并非所有参数都在包中指定)。但是为什么它在这种情况下有效并且我没有收到错误消息?
【问题讨论】: