gpt4 book ai didi

c++ - 从模板父类导入一个模板成员类型,无需重复名称

转载 作者:行者123 更新时间:2023-12-05 05:31:15 25 4
gpt4 key购买 nike

我想从模板父类导入一个模板类型,而不必输入两次名称。可能吗?

#include <vector>

struct CPU
{
using SimpleType = int;
template<typename T> using Matrix = std::vector<std::vector<T>>;
};

template<typename Target>
struct Pipeline : public Target
{
using typename Target::SimpleType; // Ok, I don't have to type 'using SimpleType = typename Target::SimpleType'

//template<typename T> using typename Target::Matrix; // Error

template<typename T>
using Matrix = typename Target::template Matrix<T>; // Ok BUT it repeats the name 'Matrix'

void ff()
{
SimpleType x;
Matrix<float> y;
}
};

int main()
{
Pipeline<CPU> pipeline;
pipeline.ff();
}

最佳答案

根据当前的 c++ 语法,您不能在 using 声明 ( source: cppreference.com ) 中包含模板 ID,因此这不会直接起作用。您既不能轻易地将它提升到命名空间级别(因为没有模板命名空间参数),也不能通过在类中使用简单的特征类来简化(因为语法与直接使用它相同)。

如果您仅将其用于例如在计算中生成变量,就是要有一个生成器函数。当你有一个 using Base::fn声明,它将所有这些函数(包括模板)带入作用域:

#include <vector>

template<typename T>
struct id_t
{
using type = T;
};

template<typename T>
id_t<T> id = {};

struct CPU
{
using SimpleType = int;
template<typename T> using Matrix = std::vector<std::vector<T>>;

template<typename T>
static constexpr auto gen_matrix_type(id_t<T>) -> Matrix<T> { return {}; }
};

template<typename Target>
struct Pipeline : public Target
{
using typename Target::SimpleType; // Ok, I don't have to type 'using SimpleType = typename Target::SimpleType

using Target::gen_matrix_type;

void ff()
{
SimpleType x;
// typename Target::template Matrix<float> y;
auto y = gen_matrix_type(id<float>);
}
};

int main()
{
Pipeline<CPU> pipeline;
pipeline.ff();
}

这与您要求的不同:您不能直接引用后代类的类型(您需要 decltype(Pipeline<CPU>::gen_matrix_type(id<float>) 而不是 Pipeline<CPU>::template Matrix<float> ),因此它不适用于所有用例,但是当您只需要在实现中生成空变量时,可能会简化这种情况。如果需要,它也可以扩展为采用 ctor args。


要考虑的另一种选择是,是否 Matrix真的应该是CPU的成员.当然,您可能想要不同的 Matrix不同基类的模板,所以这意味着引入另一个类型参数;在某种意义上,这就像将一个成员函数提升为一个全局函数,或者拥有一个 operator。作为 friend函数而不是成员函数。额外的好处是,您可以确保所有后代都拥有相同的 template输入:

#include <type_traits>
#include <vector>

template<typename Scope, typename T, typename = void>
struct MatrixType;

template<typename Scope, typename T>
using Matrix_t = typename MatrixType<Scope, T>::type;

struct CPU;

template<typename Scope, typename T>
struct MatrixType<Scope, T, typename std::enable_if<std::is_base_of<CPU, Scope>::value>::type>
{
using type = std::vector<std::vector<T>>;
};

struct CPU
{
using SimpleType = int;
};

template<typename Target>
struct Pipeline : public Target
{
using Self = Pipeline;
using typename Target::SimpleType; // Ok, I don't have to type 'using SimpleType = typename Target::SimpleType

void ff()
{
SimpleType x;
Matrix_t<Pipeline, float> y;
}
};

关于c++ - 从模板父类导入一个模板成员类型,无需重复名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74417005/

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