gpt4 book ai didi

c++ - 如何调用模板类的模板构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:04 27 4
gpt4 key购买 nike

template<typename T>
struct A
{
template<typename U>
A() {}

template<typename U>
static void f() {}
};

int main()
{
A<int>::f<int>(); // ok
auto a = A<int><double>(); // error C2062: type 'double' unexpected
}

问题在代码中是不言而喻的。

我的问题是:

如何调用模板类的模板构造函数?

最佳答案

您不能直接调用类的构造函数。如果您无法从调用中推断出构造函数的模板参数,则无法调用该特定构造函数。

您可以做的是创建某种可用于零开销扣除的类型包装器:

template <typename T>
struct type_wrapper { };

template<typename T>
struct A
{
template<typename U>
A(type_wrapper<U>) {}
};

int main()
{
auto a = A<int>(type_wrapper<double>{});
}

live example on wandbox

关于c++ - 如何调用模板类的模板构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43808848/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com