我想重载模板结构中使用朋友的函数。 我想用它来将一个类型映射到另一个类型。在下面的代码中,我想将int
类型映射到MyType
。模板的朋友功能:错误的函数调用
这里就是我所做的迄今:
void map(...){} // Worst case
// Here's the class that will overload our function
template<typename Type, typename T>
struct MakeFunction {
friend Type map(T) { return {}; }
};
// Make the function with int?
struct MyType : MakeFunction<MyType, int> {};
int main() {
// The type obtained is void, worst case choosed. The expected result is `MyType` as return type.
std::cout << typeid(decltype(map(int{}))).name() << std::endl;
return 0;
}
然后,我试过了:
template<typename T>
void map(){} // Worst case
// Here's the class that will overload our function
template<typename Type, typename T>
struct MakeFunction {
// Compilation error.
friend Type map<T>() { return {}; }
};
struct MyType : MakeFunction<MyType, int> {};
int main() {
std::cout << typeid(decltype(map<int>())).name() << std::endl;
return 0;
}
但是编译与失败:
error: defining explicit specialization ’map<T>’ in friend delcaration
如何更改声明所以选择正确的功能?或者有没有一种方法可以在没有许多模板的情况下映射类型?
注意:友情不是遗传的(根据* 11.3/10 [class.friend] *)。 – Holt
你可以在'MakeFunction'外面定义'map'吗? – Holt
在'MakeFunction'内定义它就是一个重点。我想在每次扩展时映射一个类型。在我的例子中,由于'MyType'扩展了它,它应该使用指定类型的函数'map'。 –