c++ - 具有非模板类型参数的模板函数的重载解析

标签 c++ templates c++14 overloading sfinae

#include <type_traits>
#include <vector>
#include <iostream>

namespace detail
{
template <typename T, typename U>
constexpr bool is_lvalue_reference_of_type =
    std::is_lvalue_reference<T>::value && std::is_same<std::decay_t<T>, U>::value;

// container is lvalue reference and no filter, echo back parameter
template <typename Container,
          typename = std::enable_if_t<
                is_lvalue_reference_of_type<Container, std::vector<int>>
            >
          >
const std::vector<int>& f(void *, Container && c)
{
    std::cout << "void *\n";
    return c;
}
// filter input and return a copy
template <typename Filter,
          typename = std::enable_if_t<!std::is_same_v<std::decay_t<Filter>, void *>>>
std::vector<int> f(Filter &&, const std::vector<int> &)
{
    std::cout << "Filter \n";
    return {};
}
}


template <typename T = void*>
void g(T && t = nullptr)
{
    const std::vector<int> v;
    detail::f(std::forward<T>(t), v);
}

int main(int, const char * const * const)
{
    g();
    g([](const int) {return true;});
}

void* 类型的参数时,有没有一种方法可以自动优先使用第一个模板重载? , const std::vector<int> & 是否在没有手动排除此组合的第二个重载的情况下通过?我发现手动禁用第二个重载是多余的,因为第一个重载已经将非模板类型的第一个参数指定为 void* 。目标是有一个不过滤并回显输入但仅当它是左值引用(不是绑定(bind)到 const & 的右值)的重载和另一个过滤并返回拷贝的重载。

最佳答案

Is there a way of automatically preferring the first template overload when arguments of type void*, const std::vector & are passed without manually excluding the second overload for this combination?

也许你可以添加第三个未使用的参数,int在第一次过载和long第二,调用f()0 (int 值)优先于第一个。

下面是一个完整的例子

#include <vector>
#include <iostream>

namespace detail
 {
   template <typename Container>
   std::vector<int> const & f (void *, Container && c, int)
    { std::cout << "void *\n"; return c; }

   template <typename Filter>
   std::vector<int> f (Filter &&, std::vector<int> const &, long)
    { std::cout << "Filter \n"; return {}; }
 }


template <typename T = void*>
void g (T && t = nullptr)
 {
   std::vector<int> const v;
   detail::f(std::forward<T>(t), v, 0);
 }

int main ()
 {
   g();
   g([](int const) { return true; });
 }

关于c++ - 具有非模板类型参数的模板函数的重载解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50408209/

相关文章:

c++ - 在交互式程序中使用带有 cout 和 stringstream 的预处理器指令 - C++

用于将结构类型映射到枚举的 C++ 模板?

c++ - 我可以在 lambda 中使用 constexpr 值而不捕获它吗?

c++ - 有效地从缓冲区读取值

c++ - g++ 在 static_assert 中接受 const 作为 constexpr

c++ - 如何正确使用类函数的指针

c++ - 如何在函数内调用函数?

c++ - 帮助模板特化

c++ - 部分特化消歧优先链的更好模式?

c++ - 参数列表中的 void_t 有效但不作为返回类型