gpt4 book ai didi

c++ - 如何用 double 来专门化模板类?

转载 作者:行者123 更新时间:2023-11-30 04:43:49 26 4
gpt4 key购买 nike

我编写了一个依赖于给定类型和可变参数类型的模板类,如下所示:

template<typename ConstType,typename...Inputs>
class ConstantTensor;

然后我再写一个类,这个类一般是这样定义的(假设wrong_type你想要什么类型都可以,但是和下面的特化不同):

template<typename T>
class X{
public:
using type=wrong_type;
}

我也有这样的专长:

template<typename ConstType,typename...Inputs>
class X< ConstantTensor< ConstType ,Inputs...>>
{
public:
using type=right_type;
}

我的问题是,如果我定义类型 ConstantTensor<ConstType,double>然后我想使用 X<ConstantTensor<ConstType,double>>::type ,一般情况被称为而不是特化。所以我得到wrong_type而不是 right_type .我想它必须处理 double输入...您能解释一下为什么以及如何解决这个问题吗?提前谢谢你。

编辑:这里有一段代码,我希望它能工作:

class Scalar
{};


template<typename ConstType,typename...Inputs>
class ConstantTensor
{
public:
constexpr ConstantTensor(const Inputs&...inputs)
{}
};

template<typename ConstType,typename...Inputs>
constexpr auto Constant(const Inputs&...inputs)
{return ConstantTensor<ConstType,Inputs...>(inputs...);}

template<typename T>
class X{
public:
using type=int;
};

template<typename ConstType,typename...Inputs>
class X<ConstantTensor<ConstType,Inputs...>>{
public:
using type=char;
};

int main()
{
constexpr auto delta=Constant<Scalar>(2.0);
using type= X<decltype(delta)>::type; // this is int not char
}

最佳答案

问题是

constexpr auto delta=Constant<Scalar>(2.0);

constexpr多变的;所以它也是const .

所以 decltype(delta)不是 ConstantTensor<Scalar>但是是 ConstantTensor<Scalar> const .

您可以验证添加 const在部分特化声明中

template<typename ConstType,typename...Inputs>
class X<ConstantTensor<ConstType,Inputs...> const>{ // <-- added const
public:
using type=char;
};

现在你明白了 typechar .

-- 编辑 --

OP 要求

Is there a short/elegant way to deal with both cases, const and non const, without duplicating the code?

我不知道它是否优雅,但在我看来它足够短:您可以使用一种自继承来添加以下偏特化。

template <typename T>
class X<T const> : public X<T>
{ };

所以 X<ConstantTensor<Scalar> const>继承自 X<ConstantTensor<Scalar>> .

关于c++ - 如何用 double 来专门化模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58024520/

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