如何重载 cb
函数模板以便代码能够编译?现在异常(exception)是:
error C2535: void notify_property <T> :: cb (const F &): member function already defined or declared
但模板不同。
template <typename T>
class notify_property {
public:
virtual ~notify_property() {}
//1
template <typename F, typename = std::enable_if_t<std::is_void_v<std::invoke_result_t<std::decay_t<F>>>>>
void cb(const F& task)
{
set_cb([task]
{
try { task(); }
catch (...) {}
});
}
//2
template <typename F, typename = std::enable_if_t<std::is_void_v<std::invoke_result_t<std::decay_t<F>, std::decay_t<T>>>>>
void cb(const F& task)
{
set_cb([this, task]
{
try { task(_value); }
catch (...) {}
});
}
//3
template <typename F, typename... A, typename = std::enable_if_t<std::is_void_v<std::invoke_result_t<std::decay_t<F>, std::decay_t<T>, std::decay_t<A>...>>>>
void cb(const F& task, const A &...args)
{
set_cb([this, task, args...]
{
try { task(_value, args...); }
catch (...) {}
});
}
virtual T& operator= (const T& f)
{
if (f != _value)
{
_value = f;
if (_cb != nullptr) _cb();
}
return _value;
}
virtual const T& operator() () const { return _value; }
virtual explicit operator const T& () const { return _value; }
virtual T* operator->() { return &_value; }
protected:
template <typename F>
void set_cb(const F& cb) { _cb = std::function<void()>(cb); }
std::function<void()> _cb = nullptr;
T _value;
};
回答:
//1
template <typename F, std::enable_if_t<std::is_void_v<std::invoke_result_t<std::decay_t<F>>>>* = nullptr>
void cb(const F& task)
{...}
//2
template <typename F, std::enable_if_t<std::is_void_v<std::invoke_result_t<std::decay_t<F>, std::decay_t<T>>>>* = nullptr>
void cb(const F& task)
{...}
最佳答案
typename = std::enable_if_t
如果重复是有问题的,因为 - 正如你的错误提到的 - 你多次定义相同的功能,只是用不同的默认参数。
更改每个类型模板参数
// Type parameter, with a defaulted type
typename = std::enable_if_t< ... >
// ^^^^^^^^^^^ remove!
作为函数签名一部分的非类型模板参数:
// Value (pointer) parameter, with a defaulted value
std::enable_if_t< ... >* = nullptr
// ^^^^^^^^^^^ add
(或者,像 cppreference 那样)
// Value (bool) parameter, with a defaulted value
std::enable_if_t< ..., bool> = true
// ^^^^^^^^^^^^^^ add
关于c++ - 重载函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69091389/