【发布时间】:2018-12-29 20:46:23
【问题描述】:
我想在 c++17 中有以下代码:
#include <iostream>
#include <string>
#include <type_traits>
#include <functional>
class Foo;
template<class T>
class Bar {
public:
std::function<T(Foo&)> m_fn;
template<class Fn>
Bar(Fn fn) : m_fn(fn) {};
T thing(Foo &foo) const {
return m_fn(foo);
}
};
template<class Fn>
Bar(Fn) -> Bar<decltype(std::invoke(std::declval<Fn>(),
std::declval<Foo&>()))>;
class Foo {
public:
Foo() {};
template<class T>
std::vector<T> do_thing(const Bar<T> &b) {
std::vector<T> r;
r.push_back(b.thing(*this));
return r;
}
};
std::string test(Foo &) {
return "hello";
}
int main() {
Foo foo = Foo();
// works
std::vector<std::string> s = foo.do_thing(Bar{test});
// cant deduce T parameter to do_thing
std::vector<std::string> s = foo.do_thing({test});
}
但是编译这个让我在调用do_thing时“无法推断出模板参数‘T’”。
拥有do_thing(Bar{test}) 可以解决此问题并且工作正常,但等同于真实代码等效项中的一些丑陋代码。我想让do_thing({test}) 或do_thing(test) 隐式构造一个Bar 并尽可能将其作为参数传递。
我也不想转发声明一个变量以传递给do_thing
有什么方法可以指导模板参数T 的推断,以便对do_thing 的调用可以保持干净吗?
编辑:
抱歉,编辑晚了,但在我包含的示例中,Bar 构造函数的参数被过度简化了。实际上,有一个额外的参数std::optional<std::string> desc = std::nullopt,将来可能会改变(尽管不太可能)。所以在do_thing 内部构造Bar 会有点难以维护...
【问题讨论】:
-
您不能只接受
T并在do_thing中构造Bar<T>? -
@DavisHerring 是的,但我想避免这种情况。请参阅我的编辑以获取解释
-
仅供参考,而不是
decltype(invoke(/*...*/))使用invoke_result
标签: c++ templates c++17 template-argument-deduction