[英]How do I make this template specialization with variadic arguments a friend of a class?
我有以下生成器 function:
template <typename T>
struct Wrapper {
Wrapper(T);
};
template <typename T, typename... Args>
inline Wrapper<T>
buildWrapper(Args&&... args) noexcept {
return Wrapper<T>(T(std::forward<Args>(args)...));
}
我想让它成为唯一可以创建以下 class 实例的东西,所以我将 ctor 设为私有并尝试将上述模板 function 标记为朋友。
class Bar {
private:
Bar(bool);
friend inline Wrapper<Bar> buildWrapper<Bar>(bool) noexcept;
}
但这会产生错误:
error: no function template matches function template specialization 'buildWrapper'
note: candidate template ignored: could not match 'type-parameter-0-1 &&' against 'bool'
我尝试了一些看起来合理的变体,但我只是不确定这里将模板专业化声明为朋友的正确语法是什么。
这个声明有两个问题:
friend inline Wrapper<Bar> buildWrapper<Bar>(bool) noexcept;
inline
说明符。buildWrapper
没有这种采用bool
参数的特化。 您的 function 模板需要转发引用,因此它总是需要某种对bool
的引用。正确的写法是:
friend Wrapper<Bar> buildWrapper<Bar>(bool&&) noexcept;
尽管您可能还必须另外使用其他类型的bool
参数,这很快就会变得笨拙。 更容易成为所有人的朋友:
template <typename T, typename... Args>
friend Wrapper<T> buildWrapper(Args&&...) noexcept;
没有这样的“有条件的友谊”概念可以让您只与Bar
成为朋友(例如,您不能在此处添加约束以仅限制到Bar
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.