gpt4 book ai didi

c++ - GCC/C++17 中的模板模板类问题

转载 作者:行者123 更新时间:2023-12-01 12:06:53 25 4
gpt4 key购买 nike

考虑以下 2 个重载

template<typename T>
bool test() {
return true;
}

template<template<typename ...> class T>
bool test() {
return false;
}

第一个适用于常规类,而第二个适用于未实例化的模板。
例如:
    std::cout<<test<int>()<<std::endl; <-- this yields 1
std::cout<<test<std::list>()<<std::endl; <--this yields 0

现在考虑以下模板函数:
template<typename U>
bool templfun(){
struct A{
bool f(){
return test<A>(); // <-- this gives an error
}
};
return test<A>(); // <-- this is ok
}

在 GCC 中,它为不明确的重载解析提供错误,而 Clang 编译。
有趣的是,第二次调用 test() 不会产生错误(即使在 GCC 中)。
此外,如果我删除 template<typename U>在 templfun 之上的事情,gcc 停止提示。

这是 GCC 的错误还是非法代码?

最佳答案

海湾合作委员会是错误的; struct Atemplated entity但显然不是 template (因为它不是以 template 关键字开头),所以没有歧义。

为了确认,我们可以重命名类型参数以查看 G++ 正在尝试使用模板模板重载。

template <typename X>
bool test() {
return true;
}

template <template <typename...> class Y>
bool test() {
return false;
}

template <typename U>
bool templfun() {
struct A {
bool f() {
return test<A>(); // <-- this gives an error
}
};
return test<A>(); // <-- this is ok
}

bool run() {
return templfun<int>();
}

G++ 输出:( link to godbolt )
<source>:15:27: error: call of overloaded 'test<templfun() [with U = int]::A>()' is ambiguous
15 | return test<A>(); // <-- this gives an error
| ~~~~~~~^~

<source>:2:6: note: candidate: 'bool test() [with X = templfun() [with U = int]::A]'
2 | bool test() {
| ^~~~

<source>:7:6: note: candidate: 'bool test() [with Y = templfun()::A]'
7 | bool test() {
| ^~~~

显然“ candidate: 'bool test() [with Y = templfun()::A]'”是假的。

请注意,在 C++11 之前,不允许将本地类型作为模板参数(参见 C++03 § 14.3.1.2),因此这可以解释 G++ 实现的复杂性。

关于c++ - GCC/C++17 中的模板模板类问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60278840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com