[英]C++ variadic templates
我正在使用矢量定義:
vector<lmlink_out> os{
lmlink_out(typeid(string &)),
lmlink_out(),
lmlink_out(typeid(int),typeid(char))
};
使用以下代碼有效(在類內定義):
class lmlink_out {
vector<const type_info*> parameters;
...
public:
template<typename... T, std::size_t N = sizeof...(T)>
lmlink_out(const T&... args) : parameters({&args...}) {}
使用其他會導致編譯錯誤(在類外部定義):
class lmlink_out {
vector<const type_info*> parameters;
...
public:
template<typename... T, std::size_t N = sizeof...(T)>
lmlink_out(const T&... args);
};
template<typename... T, std::size_t N = sizeof...(T)>
lmlink_out::lmlink_out(const T&... args)
: parameters({(&args...})
{
}
編譯器(gcc 版本 10.2.1 20210110 (Debian 10.2.1-6))返回:
錯誤:沒有匹配的 function 調用 'std::vector<const std::type_info*>::vector()' 374 |
: 參數({(&args...}) 注意: 候選: 'std::vector<_Tp, _Alloc>::vector(std::initializer_list<_Tp>, const allocator_type&) [with _Tp = const std::type_info* ; _Alloc = std::allocator<const std::type_info*>; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<const std::type_info*>]' 625 |
vector(initializer_list<value_type> __l, ... | ^~~~~~ /usr/include/c++/10/bits/stl_vector.h:625:43: 注意:從 '' 到 ' 的參數 1 沒有已知的轉換std::initializer_list<const std::type_info*>'
我認為兩個代碼在語義上是等效的,為什么第二個會出錯?
我需要添加另一個構造函數:
template<typename... T, std::size_t N = sizeof...(T)>
lmlink_out(const string &name, const T&... args) : name(name), parameters({&args...}) {}
但這會導致上述相同的錯誤。
您的代碼有兩個簡單的問題:
您不能重新定義模板默認 arguments,即,您需要從 ctor 的定義中刪除= sizeof...(T)
。 它只能出現在第一個聲明中。
調用parameters
ctor時有多余的'('。應該是
: parameters({&args...})
此Compiler Explorer 鏈接顯示代碼編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.