【发布时间】:2019-02-04 22:48:36
【问题描述】:
假设我们有一个看起来像这样的函数:
template <typename F, typename... A>
inline void execute(F&& functor, A&& ... args) {
std::forward<decltype(functor)>(functor)(std::forward<decltype(args)>(args)...);
}
这适用于简单的非模板函数。但是,我正在尝试完善一个模板化函数(一个相当做作的函数):
namespace detail {
template <typename CodecImpl>
class codec
{
public:
//
// Encoding
// Convenient version, returns an std::string.
static std::string encode(const uint8_t* binary, size_t binary_size);
static std::string encode(const char* binary, size_t binary_size);
...
};
class base64_rfc4648
{
public:
template <typename Codec> using codec_impl = stream_codec<Codec, base64_rfc4648>;
static CPPCODEC_ALWAYS_INLINE constexpr size_t alphabet_size() {
static_assert(sizeof(base64_rfc4648_alphabet) == 64, "base64 alphabet must have 64 values");
return sizeof(base64_rfc4648_alphabet);
}
static CPPCODEC_ALWAYS_INLINE constexpr char symbol(alphabet_index_t idx)
{
return base64_rfc4648_alphabet[idx];
}
...
};
} // namespace detail
using base64_rfc4648 = detail::codec<detail::base64<detail::base64_rfc4648>>;
尝试转发以上内容:
std::string buf("hello world");
execute(base64_rfc4648::encode, buf.c_str(), buf.size());
不起作用。模板推演失败:
注意:无法推导出模板参数'F'
它还指出:
没有匹配函数调用
'execute(<unresolved overloaded function type>, const char*, std::__cxx11::basic_string<char>::size_type)'
我该如何解决这个问题?
注意:为了便于阅读,我在上面保留了简短的信息,但如果需要更多信息,我可以添加。
【问题讨论】:
-
本质上是相同的问题,除了使用模板而不是重载函数:stackoverflow.com/questions/43171323/…
-
如果 C++ 14 是一个选项,那么接受的答案应该适合你。
-
这与转发无关。您正在尝试传入重载函数。那行不通,使用 lambda 或编写仿函数。
-
我明白了。我现在正在使用 lambda。谢谢
-
decltype(args)而不是 A 是怎么回事?
标签: c++ c++11 templates variadic-templates perfect-forwarding