【发布时间】:2021-03-31 17:40:30
【问题描述】:
我遇到了一些模板问题,我已将其范围缩小到以下示例 (C++17):
template <typename T> struct item {
operator item<const T> () const { return item<const T>(); }
};
void conversionToConstRefWorks (const item<const int> &) { }
template <typename T>
void butNotWhenTemplated (const item<const T> &) { }
int main () {
item<int> i;
item<const int> ci;
// these all compile fine:
conversionToConstRefWorks(ci);
conversionToConstRefWorks(i);
butNotWhenTemplated(ci);
// but this one fails:
butNotWhenTemplated(i);
}
在那个例子中:
-
item<T>具有到item<const T>的隐式转换运算符,并且 - 转换似乎在
conversionToConstRefWorks()中有效,但是 -
butNotWhenTemplated()中似乎错过了转换,其中item<const int>可以很好地传递,但传递item<int>无法编译。
该示例的编译失败 (GCC 9.3):
g++ --std=c++17 -W -Wall -pedantic -Wno-unused-variable const_interop.cpp -o const_interop
const_interop.cpp: In function ‘int main()’:
const_interop.cpp:54:24: error: no matching function for call to ‘butNotWhenTemplated(item<int>&)’
54 | butNotWhenTemplated(i);
| ^
const_interop.cpp:40:6: note: candidate: ‘template<class T> void butNotWhenTemplated(const item<const T>&)’
40 | void butNotWhenTemplated (const item<const T> &) {
| ^~~~~~~~~~~~~~~~~~~
const_interop.cpp:40:6: note: template argument deduction/substitution failed:
const_interop.cpp:54:24: note: types ‘const T’ and ‘int’ have incompatible cv-qualifiers
54 | butNotWhenTemplated(i);
| ^
根本错误似乎是:
类型“const T”和“int”具有不兼容的 cv 限定符
我理解字面意义上的意思,但我不明白为什么会这样。我的期望是在调用butNotWhenTemplated(i) 时应用item<int> :: operator item<const int> () const 转换运算符,就像在调用conversionToConstRefWorks(i) 时应用它一样,并且int 将被选择用于T。
我的主要问题是:为什么不编译?
我的另一个问题是:由于本文范围之外的原因,butNotWhenTemplated 必须是一个模板,并且必须为所有item 参数指定<const T>,并且我不能在调用时显式指定模板参数它。有没有办法在这些限制条件下完成这项工作?
Here it is on ideone (GCC 8.3)。
【问题讨论】:
-
但是以标准的名义,为什么this 有效? (而不是
Item<T>我使用T*) -
@RinKaenbyou 除非我误读/误解,否则我认为这是因为
int *→int const * const &转换不是在模板参数内完成的(与Item<T>→Item<const T>不同-- 你的在精神上更类似于Item<T>→const Item<T>)。例如。T和const T是同一类型,仅在 cv 限定符上有所不同,而Item<T>和Item<const T>是完全不同的类型,因为模板参数不同,然后关于推导规则的一些事情就可以了。可能是。奥托我不知道我在说什么。
标签: c++ templates gcc c++17 implicit-conversion