簡體   English   中英

專門用於非模板類的模板化構造函數

[英]specialising templated constructor of a non-template class

如何專門化非模板類的模板化構造函數? 下面的代碼可以用 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?)
$

我相信,這是 CLang 中的一個錯誤。 標准中沒有任何內容可以阻止構造函數的顯式專業化,並且 gcc 中的類似問題被認為是一個錯誤:

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

我通過搜索找到了這里,TC提到的鏈接有最終決定權(2019年)。

現在確定在構造函數模板特化中“不應指定模板參數”。 即以下代碼有效:

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

我已經確認 GCC 和 Clang 現在都接受它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM