C ++ 17。处理使用auto相关的模板参数。代码排序困难

问题描述 投票:0回答:1

我正在创建一个包含2个模板参数但相关的类模板。一个实例将用于mysql数据库。模板使用类型MYSQL初始化,并且成员函数将返回MYSQL_RES *。如果我创建带有2个参数的模板,则效果很好例如

template<class T,class R> class foo

但是随着类的相关,当指定类型T时,类型R是已知的。有什么办法编码吗?

使用自动,我可以使它正常工作。

template<class T> class foo{
 public:
auto bar();
};

具有成员函数专门化,如

 template<> auto foo<MYSQL>::bar(){MYSQL_RES *r;return r;};

但随后会遇到代码排序问题。即template <> auto foo :: bar必须在使用前实现,而不要在单独的cpp文件中实现。

我尝试过进行前向声明例如

template<> auto foo<MYSQL_RES>::bar();

但是这不起作用。

有人能以优美的方式解决此问题吗?

谢谢。

c++ templates auto
1个回答
1
投票

您可以创建特征来帮助您:

template<class T> struct myFooTrait;

template<class T> class foo
{
public:
    using R = typename myFooTrait<T>::type;
    R bar();
};

class MYSQL;
class MYSQL_RES;

template<> struct myFooTrait<MYSQL>
{
    using type = MYSQL_RES *;
};

template<>
auto foo<MYSQL>::bar() -> R { MYSQL_RES *r = /*..*/;return r;}

// Other specializations...
© www.soinside.com 2019 - 2024. All rights reserved.