我有两个模板化的类。现在我想构造一个与现有变量具有相同类型的新变量,并且具有基于该变量的模板参数。
更具体地说,我有:
template <typename T, size_t N, size_t M>
class Foo
{
public:
Foo() = default;
};
template <typename T, size_t N>
class Bar
{
public:
Bar() = default;
};
这允许我构建例如:
int main()
{
Foo<int, 2, 2> foo;
Bar<double, 3> bar;
return 0;
}
现在我想根据现有变量分配一个 Foo
或 Bar
的新变量,它具有相同的 T
,不同的 N
,和(可选的)模板参数的其余部分与现有变量相同。
例如,我想要一个可以构造
Foo<int, 2 + 2, 2>
Foo<double, 3 + 2>
我想到了一个辅助函数:
template <template <typename, size_t, class...> class X, typename T, size_t N, class... Args>
auto construct(X<T, N, Args...>&)
{
return X<T, N + 2, Args...>();
}
做例如
auto a = construct(foo);
但这让我的编译器不高兴:
error: no matching function for call to 'construct'
auto a = construct(foo);
^~~~~~~~~
note: candidate template ignored: could not match 'type-parameter-0-3' against 2
auto construct(X<T, N, Args...>&)
^
1 error generated.
答案 0 :(得分:1)
类型和非类型模板参数不容易混合。您的 construct
需要一个 template <typename, size_t, class...> class X
,即具有 1 个类型、1 个 size_t
和任意多个类型参数的模板。 Foo
不是这样。如果您将这些修复为 size_t
您的代码编译:
template <template <typename, size_t, size_t...> class X,
typename T,
size_t N,
size_t... Args> // <--- Args are size_t not types
auto construct(X<T, N, Args...>&)
{
return X<T, N + 2, Args...>();
}
// ....
int main() {
Foo<int, 2, 2> foo;
Bar<double, 3> bar;
Foo<int,2+2,2> a = construct(foo);
return 0;
}