【问题标题】:specialising templated constructor of a non-template class专门化非模板类的模板化构造函数
【发布时间】:2016-07-02 21:47:09
【问题描述】:

如何特化非模板类的模板化构造函数?下面的代码可以用 gcc 和 icc 编译,但不能用 clang 和 msvc。

代码是 a) 非法但 icc/gcc 还是编译它还是 b) 合法但 clang/msvc 由于某种原因无法编译。

复制者:

$ cat template_01.cpp
struct A
{
  template<class T>
  A(T const &t);
};

template<>
A::A<double>(double const& t) {}

int main()
{
  A a(42.0);
}

复制步骤:

$ clang++ template_01.cpp
template_01.cpp:8:4: error: qualified reference to 'A' is a constructor name rather than a type wherever a constructor can be declared
A::A<double>(double const& t) {}
   ^
template_01.cpp:8:5: error: expected unqualified-id
A::A<double>(double const& t) {}
    ^
2 errors generated.
$

$ g++ template_01.cpp
$

$ icc template_01.cpp
$

$ cl.exe template_01.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.40629 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

template_01.cpp
template_01.cpp(8) : error C2143: syntax error : missing ';' before '<'
template_01.cpp(8) : error C2988: unrecognizable template declaration/definition
template_01.cpp(8) : error C2059: syntax error : '<'
template_01.cpp(11) : error C2143: syntax error : missing ';' before '{'
template_01.cpp(11) : error C2447: '{' : missing function header (old-style formal list?)
$

【问题讨论】:

  • 使用简单的重载。
  • 删除&lt;double&gt;修复clang编译Demo

标签: c++ templates gcc visual-c++ clang


【解决方案1】:

我在这里通过搜索找到了,链接 T.C.提到有最终决定权(2019年)。

现在确定在构造函数模板特化中“不应指定模板参数”。 IE。以下代码有效:

template<>
A::A(double const& t) {}

而且我已经验证 GCC 和 Clang 现在都接受它了。

【讨论】:

    【解决方案2】:

    我相信,这是 CLang 中的一个错误。标准中没有任何内容可以阻止构造函数的显式特化,并且 gcc 中的类似问题被认为是一个错误:

    https://gcc.gnu.org/bugzilla/show_bug.cgi?id=9050

    【讨论】:

    • 正如稍后在 GCC bugzilla 线程中所讨论的,这是CWG 581
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多