C++推断指向成员模板参数的指针
C++ deduce pointer to member template parameter
我正在尝试使用 C++17 个功能为词典比较编写模板化版本:
#include <type_traits>
#include <set>
#include <vector>
#include <iostream>
namespace compare
{
template <typename T, auto P, auto ...Ps>
bool less(const T &t1, const T &t2)
{
if constexpr (sizeof...(Ps) == 0)
{
return t1.*P < t2.*P;
}
else
{
if (t1.*P == t2.*P)
{
return less<Ps...>(t1, t2);
}
else
{
return t1.*P < t2.*P;
}
}
}
}
struct my_type
{
int i = 0;
std::set<int> s;
};
int main()
{
my_type t1, t2;
t2.i = -1;
std::cout << std::boolalpha << compare::less<my_type, &my_type::i, &my_type::s>(t1, t2) << std::endl;
return 0;
}
但是,我的示例无法使用最新版本的 GCC 进行编译:
main.cpp: In instantiation of 'bool compare::less(const T&, const T&) [with T = my_type; auto P = &my_type::i; auto ...Ps = {&my_type::s}]':
main.cpp:42:88: required from here
main.cpp:16:23: error: no matching function for call to 'less<&my_type::s>(const my_type&, const my_type&)'
return less<Ps...>(t1, t2);
~~~~~~~~~~~^~~~~~~~
main.cpp:6:7: note: candidate: template<class T, auto P, auto ...Ps> bool compare::less(const T&, const T&)
bool less(const T &t1, const T &t2)
^~~~
main.cpp:6:7: note: template argument deduction/substitution failed:
有趣的是,编译器输出没有说明无法推断出哪个模板参数。我知道如何以 C++17 之前的方式实现这一点。我做错了什么?
您在less<Ps...>
中缺少T
。
namespace compare
{
template <typename T, auto P, auto ...Ps>
bool less(const T &t1, const T &t2)
{
if constexpr (sizeof...(Ps) == 0)
{
return t1.*P < t2.*P;
}
else
{
if (t1.*P == t2.*P)
{
return less<T, Ps...>(t1, t2);
}
else
{
return t1.*P < t2.*P;
}
}
}
}
现场观看
旁白:为了适应标准库定义概念 Compare 的方式,我建议删除 ==
的使用,而是使用
if (return t1.*P < t2.*P)
{
return true;
}
if (return t2.*P < t1.*P)
{
return false;
}
return less<T, Ps...>(t1, t2);
相关文章:
- 使用指向成员的指针将成员函数作为参数传递
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 修改函数中的指针(将另一个指针作为参数传递)
- Clang bug?使用指针作为模板参数
- MSVC将仅移动结构参数解释为指针
- 非类型指针和引用模板参数,以及在编译时如何/为什么解析它们.c++
- 如何使用非类型模板参数传入指向数组的指针
- 将成员函数指针作为参数传递给模板方法
- 匹配函数指针作为模板参数?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 通过智能指针和转换对基本模板参数进行模板推导
- 为函数定义符号不明确的指针参数
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 将函数参数完美转发到函数指针:按值传递呢?
- 保留函数指针模板参数
- 如何构造一个以可变参数指针函数作为成员的类?
- 指向对象的非类型模板参数指针
- c++ 使用 *& as 参数(指针乐趣,三级树方法)