带Concept的C++模板函数调用歧义及错误匹配问题问询
C++ Concept 匹配问题解析
原始测试代码
#define P std::cout << __PRETTY_FUNCTION__ << '\n' template <typename ... arg_pack> concept is_tuple = requires(std::tuple<arg_pack ...>) { true; }; template <typename ... arg_pack> concept is_variant = requires(std::variant<arg_pack ...>) { true; }; template <is_tuple type_t> void X(const type_t &t) { P; } // A //template <is_variant type_t> void X(const type_t &v) { P; } // B void X(int) { P; } int main() { std::tuple<int> t; std::variant<int> v; X(t); X(v); X(0); return 0; }
运行输出
void X(const type_t &) [type_t = std::tuple<int>] void X(const type_t &) [type_t = std::variant<int>] void X(int)
取消注释B行后的编译错误
error: call to 'X' is ambiguous X(t); ^ note: candidate function [with type_t = std::tuple<int>] template <is_tuple type_t> void X(const type_t &t) { P; } ^ note: candidate function [with type_t = std::tuple<int>] template <is_variant type_t> void X(const type_t &v) { P; } ^ error: call to 'X' is ambiguous X(v); ^ note: candidate function [with type_t = std::variant<int>] template <is_tuple type_t> void X(const type_t &t) { P; } ^ note: candidate function [with type_t = std::variant<int>] template <is_variant type_t> void X(const type_t &v) { P; } ^ 2 errors generated.
疑问点
- 注释B行时,调用
X(v)为何未触发编译错误,反而调用了错误的模板函数? - 取消注释B行后,明明
std::is_same_v<std::tuple<int>, std::variant<int>>为false,为何调用X(t)和X(v)都会出现歧义?
正确的Concept实现方案
感谢Jan Schultke及Stack Overflow社区的帮助,以下是可行的is_tuple和is_variant替代实现:
template <typename type_t> concept is_tuple = []<typename ... arg_pack>(std::tuple<arg_pack ...>){ return true; }(type_t{}); template <typename type_t> concept is_variant = []<typename ... arg_pack>(std::variant<arg_pack ...>){ return true; }(type_t{});
内容的提问来源于stack exchange,提问作者PaperBirdMaster
相关产品推荐
相关产品推荐

