c++ - 从其他容器中辨别 smart_pointer 的模板函数

标签 c++ templates c++11 overloading template-templates

考虑以下模板函数:

template <class T>
const T* DoSomething(const T& t)
{
    auto& id = typeid(T);
    cout << "Type is " << id.name() << ", and we have a ";
    cout << "ref of one\n";
    return &t;
}

template <class T>
T* DoSomething(T* t)
{
    auto& id = typeid(T);
    cout << "Type is " << id.name() << ", and we have a ";
    cout << "pointer to one \n";
    return t;
}

template <class T, template <class> class container>
T* DoSomething(const container<T>& t)
{
    auto& type_id = typeid(T);
    auto& container_id = typeid(container<T>);
    cout << "Type is " << type_id.name() << ", and we have a ";
    cout << container_id.name() << "of one\n";
    return t.get();
}

template <class T, template <class,class> class container, template <class> class deleter = default_delete>
T* DoSomething(const container<T, deleter<T>>& t)
{
    auto& type_id = typeid(T);
    auto& container_id = typeid(container<T,deleter<T>>);
    cout << "Type is " << type_id.name() << ", and we have a ";
    cout << container_id.name() << "of one\n";
    return t.get();
}

目标是能够将普通引用、指针或智能指针传递给它们,并使用重载和模板特化来调用正确的函数。以下驱动代码按预期工作:

char r('r');
DoSomething(r);  
DoSomething(&r);
shared_ptr<char> s(new char ('s'));
unique_ptr<char> u(new char ('u'));
DoSomething(s);
DoSomething(u);

但是,考虑一下如果我们尝试这样做会发生什么:

vector<int> v {1,2};
DoSomething(v);

现在,我们得到一个编译错误。编译器决定使用的 DoSomething 版本是第四个。在其中,我们引用了函数 get(),而 vector 没有。如果编译器以某种方式选择 DoSomething 的第一个定义,它将编译正常,并按我的意图工作。

那么我可以限制第 3 和第 4 个特化仅在模板模板参数包含 get() 方法时匹配吗?有什么方法可以实现这一点,也许是使用特征、SFINAE 或其他一些更高级的模板技术?

最佳答案

The version of DoSomething that the compiler decides to use is the 4th one.

因为 std::vector<T, std::allocator<T>>与模板参数 container 完全匹配和 std::allocator<T>与模板参数 deleter 完全匹配, 和 const container<T, deleter<T>>&const T& 更专业因此第 4 个重载被选为函数模板的部分排序规则的最佳匹配。

So can I restrict the 3rd and 4th specializations to only be matched when the template template parameter contains a get() method?

是的,你可以告诉编译器函数返回任何t.get()返回:

template <class T, template <class> class container>
auto DoSomething(const container<T>& t) -> decltype(t.get())
{
    auto& type_id = typeid(T);
    auto& container_id = typeid(container<T>);
    cout << "Type is " << type_id.name() << ", and we have a ";
    cout << container_id.name() << "of one\n";
    return t.get();
}

如果t.get()不是有效表达式,则模板参数推导失败,因为参数 T无法成功替换到函数签名中,因此该函数将不是可行的重载,将使用第一个重载。

关于c++ - 从其他容器中辨别 smart_pointer 的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19976114/

相关文章:

c++ - 如何在Windows中模拟注册表进行程序测试?

c++ - friend 类无法访问 protected 成员

c++ - 为什么 std::accumulate 对于标准数组会有这样的行为?

c++ - 如果我只使用一个翻译单元使用 extern 模板类,为什么我不会收到链接错误?

c++ - 为什么编译器在这种情况下会选择不正确的函数重载?

c++ - 将右值引用参数转换为右值引用?

c++ - 如何通过cimg获取rgb值?

C++ 全局重载运算符=

c++ - 如何为编译时已知的参数的多个值编译函数

c++ - 如果不键入别名类型的完整声明,则无法从单独文件中的类模板定义访问类型别名