所以当我有这样的代码时:
shared_ptr<Foo> bar (my_normal_operator<Foo>(mumble));
即使类型 Foo
来自左侧字段,它也起作用,因为返回类型仅通过给定内容的"加法"模式生成:
template <typename Target, typename Source>
shared_ptr<Target> my_normal_operator(Source src)
{
/* ... whatever ... */
}
但是,如果情况看起来像这样呢:
shared_ptr<Foo> bar (my_pointer_operator<Foo*>(mumble));
它需要某种方法来将指针从类型上拉开。 我四处寻找并找到了 std::remove_pointer,但一个天真的应用程序给出了"类型/值不匹配":
template <typename Target, typename Source>
shared_ptr< std::remove_pointer<Target>::type > my_pointer_operator(Source src)
{
/* ... whatever ... */
}
我其实没想到它会起作用...但我把它放在这里是为了表达我正在寻找的意图!
叹息。 每次我踏入任何具有模板和特征的新领域时,我都会觉得自己是那些"我不知道我在做什么"的模因动物之一。 :-/
你需要typename
:
template <typename Target, typename Source>
shared_ptr< typename std::remove_pointer<Target>::type >
my_pointer_operator(Source src)
{
/* ... whatever ... */
}
因为std::remove_pointer<Target>::type
的类型取决于模板参数。
就个人而言,我会将Target
保留为Foo
并在my_pointer_operator
使用typename std::add_pointer<Target>::type
的定义范围内,因此调用者可以更直接地指定返回值。函数名称给出了实现的差异。