好吧,你不应该真的这样做,但是你去吧:) 使用 boost::preprocessor:
#include "stdafx.h"
#include <vector>
void somefunction(int p1)
{ std::cout << p1 << " " << std::endl;}
void somefunction(int p1, int p2)
{ std::cout << p1 << " " << p2 << std::endl;}
void somefunction(int p1, int p2, int p3)
{ std::cout << p1 << " " << p2 << " " << p3 << std::endl;}
void somefunction(int p1, int p2, int p3, int p4)
{ std::cout << p1 << " " << p2 << " " << p3 << " " << p4 << std::endl;}
#define MAX_ARGS 4
#include <boost/preprocessor/repetition.hpp>
void UnpackVector(const std::vector<int> &v)
{
#define MACRO(z, n, _) \
case n: somefunction(\
BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PP_INC(n), v[,]BOOST_PP_INTERCEPT) \
);break;
switch(v.size() - 1)
{
BOOST_PP_REPEAT(MAX_ARGS, MACRO, nil)
}
}
void Run()
{
int v_[] = { 42, 41, 40, 39 };
std::vector<int> v(v_, v_ + sizeof(v_) / sizeof(int));
UnpackVector(v);
}
只是为了笑声。