【发布时间】:2016-06-14 06:21:31
【问题描述】:
我正在尝试使用朋友重载模板结构内的函数。
我想用它来将一种类型映射到另一种类型。在下面的代码中,我想将类型 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])。
-
你能在
MakeFunction之外定义map吗? -
在
MakeFunction中定义它是重点。我想在每次扩展时映射一个类型。在我的示例中,由于MyType扩展了它,它应该使具有指定类型的函数map可用。 -
@GuillaumeRacicot 这行不通,因为如果在类中定义的友元函数仅在该范围内可见。如果你想让它在外面可见,那么你必须把它放在那个范围内,在你的情况下是全局的。
-
我之前在全局范围内声明了它,但这迫使我的库的用户手动添加它。相反,我想提供
MakeFunction结构,以便我的库的用户可以扩展以在“类型映射”中添加类型
标签: c++ templates c++11 friend