我具有以下构建器功能:
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)...));
}
我想使它成为唯一可以创建以下类的实例的东西,因此我将ctor设为私有,并尝试将上述模板函数标记为朋友。
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'
我已经尝试了一些看起来合理的变体,但是我不确定在这里将模板专门化声明为朋友的正确语法是什么。
此声明有两个问题:
inline
specifier here.buildWrapper
that takes abool
argument. Your function template takes forwarding references, so it would always take some kind of reference tobool
.正确的拼写是:
Although you probably would then have to additionally friend the other kinds of
bool
parameters, which gets unwieldy quickly. Easier to just friend all of 'em:There's no such concept of "conditional friendship" that would let you just friend the
Bar
ones (e.g. you can't add constraints here to just limit to theBar
s).