C++ - 使模板化 Typedef 公开并跨包含文件访问
C++ - making templated typedef public and accessibe across include files
我在 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>();
}
不,模板参数不会从参数隐式传播。
相关文章:
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 派生的 wxPanel 控件如何访问其中包含 wxDialog 中的数据?
- 访问包含矢量对的映射的值
- 循环访问还包含未使用元素的字符串数组
- 如何使用包含内部类的类实例有效地从内部类访问成员?
- 访问包含P的有效索引时返回空格的C++字符串
- 如果包含引用成员的类中缺少原始变量,为什么它仍然可以访问?
- C/C++ 包含点的宏参数(成员访问运算符)
- 无法从多态嵌套类访问包含类的成员
- 我可以从C++访问包含QtObject的QQmlContext吗?
- 如何从另一个包含目录中的标头访问包含目录中的标头
- shared_ptr - 从包含的对象内部访问
- 访问其他抽象类,而无需在C 中包含参考
- 如何使用指向该数组的指针访问结构数组中包含的结构中的字段?[C++]
- 对象如何访问所包含的类的属性
- 如何访问C数组中包含的valarray中的元素
- 使用 JNA 访问包含 vector<char* 的结构>
- 在类组合中,使包含的类可以访问容器类变量
- Boost::p tree - 访问列表中包含的属性树节点
- 访问注册表数据以设置链接器和包含路径