与参数匹配的朋友模板函数实例化 [英] Friend template function instantiations that match parameter
问题描述
我有一个模板类,应该有一个朋友:一个 make_object
函数,该函数允许推导某些类型和值.我希望只与模板类类型匹配的那些实例化成为朋友.我的代码的简化版本如下:
I have a template class that should have a friend: a make_object
function that allows to deduct certain types and values. I wish to make friends only those instantiations that match the types of the template class. The simplified version of my code is below:
template<size_t S, typename T>
class Object {
private:
Object(T t);
template<typename U, typename... Args>
friend auto make_object(U, Args... args);
};
template<typename U, typename... Args>
inline auto make_object(U u, Args... args)
{
constexpr size_t S = sizeof...(Args);
return std::unique_ptr<Object<S, U>>(new Object<S, U>(u));
}
以该代码为例,我希望只将 typename U
与对象的 typename T
匹配的 make_object
的那些实例化作为朋友.那有可能吗?
Taking this code as an example I wish to make friends only those instantiations of make_object
whose typename U
matches the typename T
of the object. Is that even possible?
推荐答案
如果您想拥有一个朋友模板,则可以像您的示例一样将模板的所有实例设为一个朋友,或者可以将其完全专门化.一个朋友.
If you want to have a friend template, you can make all the instatiations of the template a friend, like in your example, or you can make a full specialization a friend.
不幸的是,两者之间没有任何东西.
There is nothing in between unfortunately.
要解决此问题,您可以将 make_object
函数包装在模板类中,并将该模板类作为朋友.
To work around that you could wrap your make_object
function in a template class and make that template class a friend.
#include <type_traits>
#include <iostream>
#include <memory>
template<typename U>
struct object_maker;
template<std::size_t S, typename T>
class Object {
private:
Object(T) {}
friend struct object_maker<T>;
};
template<typename U>
struct object_maker
{
template<typename... Args>
static auto make_object(U u, Args... args)
{
constexpr std::size_t S = sizeof...(Args);
return std::unique_ptr<Object<S, U>>(new Object<S, U>(u));
}
};
int main()
{
auto obj = object_maker<int>::make_object(7);
static_assert(std::is_same_v<decltype(obj), std::unique_ptr<Object<0,int>>>);
}
这篇关于与参数匹配的朋友模板函数实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!