C++ - 使模板化 Typedef 公开并跨包含文件访问

C++ - making templated typedef public and accessibe across include files

本文关键字:包含 访问 文件 Typedef C++      更新时间:2023-10-16

我在 c++ 中有一个模板化的 typedef(据我所知

,这些是不合法的(。

基本上,这样的 typedef 旨在避免在我的代码中写满长类型名(我希望能够写typeA someVariable;而不是typename Foo<T,N,P>:: typeA someVariable;(。

请在下面找到我想要实现的代码。

#ifndef FOO
#define FOO

template <class T, class N, class P>
class Foo
{
 public:
        typedef T typeA;
        Foo();
};
template <class T, class N, class P>
Foo<T, N, P>::Foo(){}

#endif

#ifndef FOOUSER
#define FOOUSER
#include "Foo.h"
template <class T, class N, class P>
typedef typename Foo<T,N,P>::typeA typeA;
template <class T, class N, class P>    
typeA fooUser(Foo<T,N,P> foo)
{
     typeA typeAInstance;

     // some code;

     return typeAInstance;
}

#endif

#include <cstdlib>
#include <iostream>

#include "FooUser.h"
using namespace std;

typedef int dummyT1;
typedef int dummyT2;
typedef int dummyT3;
int main(int argc, char *argv[])
{

    typeA typeAObject;
    Foo<dummyT1, dummyT2, dummyT3> foo=Foo<dummyT1, dummyT2, dummyT3>();

    //somecode here
    typeAObject=fooUser(foo);

    system("PAUSE");
    return EXIT_SUCCESS;
}

所以我在文件fooUser.h中声明了类型,在顶部,外部函数someFunction,以便使它们普遍可访问。 但是,模板化的问题在C ++中是不合法的。我正在使用C++98。

因此参数化类型别名(引入 C++11(,例如

template <typename T>
using typeA = typename Foo<T>::TypeA;

不是一种选择。

知道我的语法不合法,我正在寻找替代解决方案。

您可以创建一个模板容器来减轻负担。

template <class A, class B, class C>
struct TemplateContainer {
    typedef A A_t;
    typedef B B_t;
    typedef C C_t;
};
template <class TC>
class User {
public:
    typedef typename TC::A_t A_t;
    typedef typename TC::B_t B_t;
    typedef typename TC::C_t C_t;
private:
    A_t _a;
    B_t _b;
    C_t _c;
public:
    User(A_t a, B_t b, C_t c) :
        _a(a), _b(b), _c(c)
    {}
};

template <class TC>
User<TC> Usage() {
    typename User<TC>::A_t a;
    typename User<TC>::B_t b;
    typename User<TC>::C_t c;
    User<TC> user(a,b,c);
    // ...
    return user;
}
int main() {
    typedef TemplateContainer<int,double,char> TC;
    User<TC> user=Usage<TC>();
}

不,模板参数不会从参数隐式传播。