---
title: "几个不同逻辑间参数传递弱化的技巧"
author: "lin_style"
date: "2010-07-24T23:25:03Z"
tags: ["框架"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-07-24T23:25:03Z"
id: 720583
url: "https://lin-style.iteye.com/blog/720583"
---

**1.线程间**

 

```
HANDLE WINAPI CreateThread(
  __in          LPSECURITY_ATTRIBUTES lpThreadAttributes,
  __in          SIZE_T dwStackSize,
  __in          LPTHREAD_START_ROUTINE lpStartAddress,
  __in          LPVOID lpParameter,
  __in          DWORD dwCreationFlags,
  __out         LPDWORD lpThreadId
);
```

 

比如它的第四个参数  LPVOID lpParameter, 接受到后，通过一个强转成自己所需要的类型。最大的优点是类型上的直接转换显得更直观。但是在一些框架模式上的封装就显得很薄弱。

**2.联合结构(union)**

 

```
typedef struct in_addr {
        union {
                struct { UCHAR s_b1,s_b2,s_b3,s_b4; } S_un_b;
                struct { USHORT s_w1,s_w2; } S_un_w;
                ULONG S_addr;
        } S_un;
```

 

这是套接字接口里的一个写法，可以把几种不同平台下的代码写在一起。 这种方法更多是为了兼容性。 

**3.动态(virtual)**

比如一个线程封装得代码可以这样写：

```
class IThread
{
public:
	virtual S32 Run()=0;	
	virtual S32 Exit()=0;
};

static U32 WINAPI ThreadProc(void* param)
{
	S32 nResult;
	ThreadCtrl *pTC = (ThreadCtrl *)param;

  nResult = pTC->pIThread->Run();
	
	return 0;
}

class CThreadPool
{
public:
	int ExecuteTask(IThread *p)
	{
	    _beginthreadex(NULL, 0, ThreadProc, this, 0, ..);
	}

};
```

 通过继承IThread的run接口，然后交给CThreadPool统一处理。通过指针和动态，实现了原先对接口参数显示传递的隐藏

 

 

**4.模板**

这就没什么好说的了，编译的时候特化。不好的地方就是代码膨胀。

个人更喜欢第一种的使用和第三种的封装的结合。