gpt4 book ai didi

c++ - 通过转换运算符推导模板参数类型

转载 作者:IT老高 更新时间:2023-10-28 22:14:54 30 4
gpt4 key购买 nike

我看到了来自 C++ 11 标准 (n3337, 14.8.2.3/7) 的示例

struct A {
template <class T> operator T***();
};
A a;
const int * const * const * p1 = a; // T is deduced as int, not const int

并尝试通过不同的编译器重现它。我通过在转换函数中添加类型为 T 的声明对示例进行了一些更改

struct A {
template <class T> operator T***()
{
T t; //if T==const int, then it is error (uninitialized const)
return nullptr;
}
};
A a;
const int * const * const * p1 = a;

int main(){}

所有编译器(VS2014、gcc 5.1.0 和 clang 3.5.1)在声明“t”时都会出错,这意味着 T 被推导出为 const int。这是为什么?是扩展名吗?

最佳答案

这已被 CWG issue #349 报道,由 EDG C++ front end 的开发者打开(显然是推导出 int,而不是 const int):

We ran into an issue concerning qualification conversions when doing template argument deduction for conversion functions.

The question is: What is the type of T in the conversion functions called by this example? Is T "int" or "const int"?

If T is "int", the conversion function in class A works and the one in class B fails (because the return expression cannot be converted to the return type of the function). If T is "const int", A fails and B works.

Because the qualification conversion is performed on the result of the conversion function, I see no benefit in deducing T as const int.

In addition, I think the code in class A is more likely to occur than the code in class B. If the author of the class was planning on returning a pointer to a const entity, I would expect the function to have been written with a const in the return type.

Consequently, I believe the correct result should be that T is int.

struct A {
template <class T> operator T***() {
int*** p = 0;
return p;
}
};

struct B {
template <class T> operator T***() {
const int*** p = 0;
return p;
}
};

int main()
{
A a;
const int * const * const * p1 = a;
B b;
const int * const * const * p2 = b;
}

We have just implemented this feature, and pending clarification by the committee, we deduce T as int. It appears that g++ and the Sun compiler deduce T as const int.

这只会使引用的段落存在(它在 C++03 中不存在!),并且可能被编译器开发人员忽略了。

关于c++ - 通过转换运算符推导模板参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30172533/

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