Domanda

I have a templated typedef (sort of as I know thery are not legal) in c++.

basically, such typedefs are meant to avoid writing all over my code long typenames (I want to be able to write typeA someVariable; instead of typename Foo<T,N,P>:: typeA someVariable;).

Please find below a code of what I am trying to achieve.

#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;
}

So I have declared the types in file fooUser.h, at the top, outside function someFunction in order to make them universally accessible. the problem, however, that templated are not legal in c++. I am using C++98.

Therefore parametrized type aliases (introduced into C++11) such as

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

are not an option.

knowing my syntax is not legal, I am looking for an alternative solution.

È stato utile?

Soluzione

You could create a template container to reduce the burden.

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>();
}

Altri suggerimenti

No, template parameters do not implicitly propagate from arguments.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top