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

Template argument type deduction by conversion operator

我看到了来自 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, opened by a developer of the 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 中不存在!),并且可能被编译器开发人员忽略了。