473,771 Members | 2,394 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

is there a way to call a function depending on an integer at runtime?

I have this scenario: several arrays for which I have their fixed
values at compilation time. Now, at runtime I need to access a
specific array depending on an integer but I want to avoid if and
switch statements.

My first approach was to rely on partial template specialization.
Therefore, I have:

// .h file
template <int vSomeClass;

template <struct SomeClass<1{
static double loc(unsigned short i) {
return loc_[i];
}
static const double loc_[1];
};
template <struct SomeClass<2{
static double loc(unsigned short i) {
return loc_[i];
}
static const double loc_[2];
};
// and so on until 30 partial specializations

// .cpp file
const double SomeClass<1>::l oc_[] = { 0.4 };
const double SomeClass<2>::l oc_[] = { 0.2, 0.6 };
// and so on until 30 partial specializations

so I called the function like this:

double location = SomeClass<3>::l oc(2);

Well, this approach worked fine until I changed the code so that the
integer is not known until runtime. So the question is...
Is there a way to do the same at runtime without having a switch or if
statement? Is there a way to do function overloading at runtime? I
thought that I could have something like the following:

struct SomeClass {

int val;
SomeClass(int v) : val(v) {}

double loc(unsigned short i) {
return locImpl(classB( val),i);
}
double locImpl(classB( 1), int i) {
const double SomeClass<1>::l oc_[] = { 0.4};
return loc_[i];
}
double locImpl(classB( 2), int i) {
const double SomeClass<2>::l oc_[] = { 0.2, 0.6 };
return loc_[i];
}
};

and convert the integer to some class and rely on function
overloading, but I couldn't find a way to do this. Any ideas? Thank
you,


Dec 29 '07
12 2310
fl
On 29 déc, 15:09, aaragon <alejandro.ara. ..@gmail.comwro te:
On Dec 29, 10:52 am, "Daniel T." <danie...@earth link.netwrote:


aaragon <alejandro.ara. ..@gmail.comwro te:
The problem with using a map is that it needs to be instantiated
with every element in it (all vectors needed to be created). I
wanted to use a function because in that way only the vectors that
I use are initialized. Most likely, I will be using only 1 of those
30 vectors for each run, so it doesn't make sense to initialize ALL
of them.
Unless a single run is extremely fast, and you will be running this
program thousands of times per second, the extra time it take to
initialize all of the vectors is irrelevant. And if the run is extremely
fast and you are running the program thousands of times per second, then
you should be embedding this code in a program that makes several passes
per run.
So yes, it does make sense to initialize all of them.

Ok, so I decided to follow your advice but with a little twist.
Instead of having a map to a vector, I will have now a map to function
pointers. Inside those functions the arrays (known at compilation
time) are declared static so they're initialized only once (when I
call the function the first time). In this way, I don't need to
initialize what I won't use. Also, I don'tneed to have annoying switch
or if blocks. It looks like this:

// .h file
template <int v>
double loc(size_t);
// forward declarations of function specializations (defined in .cxx
file)
template <>
double loc<1>(size_t);
template <>
double loc<2>(size_t);
// and so on

template <
class MapPolicy = std::map<size_t , double (*)(size_t)>

struct Map {

* typedef MapPolicy MapType;
* MapType loc_;

* Map() : loc_() {
* // add location function pointers
* loc_[1] = &loc<1>; * *// ERROR!!!
* loc_[2] = &loc<2>; * *// ERROR!!!
* // and so on
* }
* inline double loc(size_t i, size_t gp) {
* * return loc_[gp](i);
* }

};

// .cxx file, partial specializations for the function
template<>
double loc<1>(size_t i) {
* static const double loc[] = { 0.4 };
* return loc[i];}

template<>
double loc<2>(size_t i) {
* static const double loc[] = { 0.2, 0.6 };
* return loc[i];}

// and so on until 30

Ok, this looks good and it's just what I want. However, for some
strange reason that I really don't see, I cannot compile this code. At
those ERROR lines I have the following message:

testMap.h: In constructor 'fea::Map<MapPo licy>::Map()':
testMap.h:36: error: expected primary-expression before ';' token

It doesn't allow me to take the address of the templated function. The
strange thing is that I can do the same from the main.cxx file, that
is:

// main.cxx

* * std::map<size_t , double (*)(size_t)loca tion;

* * location[1] = &loc<1>;
* * location[2] = &loc<2>;

* * cout<<"what the -"<<location[2](1)<<endl;

works fine! Is this a problem with my compiler or there is something
wrong with the syntax? I'm using gcc version 4.1.2. I know, I know...
I could just use regular functions and call them loc1, loc2 and so on
and forget about the template (this will definitely work), but hey,
I'm learning day by day and I just cannot give up that easily, right?

a²- Masquer le texte des messages précédents -

- Afficher le texte des messages précédents -
Hi,
I get the following error message. Why? What's wrong with me? Thanks.

error C2039:'map' is not a member of 'std'
----------------
// .h file
#include <iostream>

template <int vdouble loc(size_t); // forward declarations of
function specializations (defined in .cxx file)
template <double loc<1>(size_t);
template <double loc<2>(size_t); // and so on
------------
#include <iostream>
#include "SomeClass. h"
using std::cout;
using std::endl;

int main()
{
std::map<size_t , double (*)(size_t)loca tion;

location[1] = &loc<1>;
location[2] = &loc<2>;
cout<<"using loc<1>: "<<loc<1>(1)<<e ndl;

return 0;
}
Dec 30 '07 #11
On Dec 29, 7:56 pm, fl <rxjw...@gmail. comwrote:
On 29 déc, 15:09, aaragon <alejandro.ara. ..@gmail.comwro te:
On Dec 29, 10:52 am, "Daniel T." <danie...@earth link.netwrote:
aaragon <alejandro.ara. ..@gmail.comwro te:
The problem with using a map is that it needs to be instantiated
with every element in it (all vectors needed to be created). I
wanted to use a function because in that way only the vectors that
I use are initialized. Most likely, I will be using only 1 of those
30 vectors for each run, so it doesn't make sense to initialize ALL
of them.
Unless a single run is extremely fast, and you will be running this
program thousands of times per second, the extra time it take to
initialize all of the vectors is irrelevant. And if the run is extremely
fast and you are running the program thousands of times per second, then
you should be embedding this code in a program that makes several passes
per run.
So yes, it does make sense to initialize all of them.
Ok, so I decided to follow your advice but with a little twist.
Instead of having a map to a vector, I will have now a map to function
pointers. Inside those functions the arrays (known at compilation
time) are declared static so they're initialized only once (when I
call the function the first time). In this way, I don't need to
initialize what I won't use. Also, I don'tneed to have annoying switch
or if blocks. It looks like this:
// .h file
template <int v>
double loc(size_t);
// forward declarations of function specializations (defined in .cxx
file)
template <>
double loc<1>(size_t);
template <>
double loc<2>(size_t);
// and so on
template <
class MapPolicy = std::map<size_t , double (*)(size_t)>
struct Map {
typedef MapPolicy MapType;
MapType loc_;
Map() : loc_() {
// add location function pointers
loc_[1] = &loc<1>; // ERROR!!!
loc_[2] = &loc<2>; // ERROR!!!
// and so on
}
inline double loc(size_t i, size_t gp) {
return loc_[gp](i);
}
};
// .cxx file, partial specializations for the function
template<>
double loc<1>(size_t i) {
static const double loc[] = { 0.4 };
return loc[i];}
template<>
double loc<2>(size_t i) {
static const double loc[] = { 0.2, 0.6 };
return loc[i];}
// and so on until 30
Ok, this looks good and it's just what I want. However, for some
strange reason that I really don't see, I cannot compile this code. At
those ERROR lines I have the following message:
testMap.h: In constructor 'fea::Map<MapPo licy>::Map()':
testMap.h:36: error: expected primary-expression before ';' token
It doesn't allow me to take the address of the templated function. The
strange thing is that I can do the same from the main.cxx file, that
is:
// main.cxx
std::map<size_t , double (*)(size_t)loca tion;
location[1] = &loc<1>;
location[2] = &loc<2>;
cout<<"what the -"<<location[2](1)<<endl;
works fine! Is this a problem with my compiler or there is something
wrong with the syntax? I'm using gcc version 4.1.2. I know, I know...
I could just use regular functions and call them loc1, loc2 and so on
and forget about the template (this will definitely work), but hey,
I'm learning day by day and I just cannot give up that easily, right?
a²- Masquer le texte des messages précédents -
- Afficher le texte des messages précédents -

Hi,
I get the following error message. Why? What's wrong with me? Thanks.

error C2039:'map' is not a member of 'std'
----------------
// .h file
#include <iostream>

template <int vdouble loc(size_t); // forward declarations of
function specializations (defined in .cxx file)
template <double loc<1>(size_t);
template <double loc<2>(size_t); // and so on
------------
#include <iostream>
#include "SomeClass. h"
using std::cout;
using std::endl;

int main()
{
std::map<size_t , double (*)(size_t)loca tion;

location[1] = &loc<1>;
location[2] = &loc<2>;
cout<<"using loc<1>: "<<loc<1>(1)<<e ndl;

return 0;

}
You forgot to put 'using std::map;' or just put 'using namespace std;'
and don't forget to implement the actual loc<vfunctions in the cpp
file.


Dec 30 '07 #12
aaragon <al************ **@gmail.comwro te:
The memory in your approach is the same (the executable
will have the same size) but the run time will be much less if I only
initialize what I need.
"More computing sins are committed in the name of efficiency (without
necessarily achieving it) than for any other single reason - including
blind stupidity." - W.A. Wulf

How much less is "much less"?
Dec 30 '07 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
6542
by: Kurt Van Campenhout | last post by:
Hi, I am trying to get/set Terminal server information in the active directory on a windows 2000 domain. Since the ADSI calls for TS don't work until W2K3, I need to do it myself. I'm fairly new to VB.NET, so I need some help. Here is a code snippit :
5
2317
by: SStory | last post by:
Hi all, I really needed to get the icons associated with each file that I want to show in a listview. I used the follow modified code sniplets found on the internet. I have left in commented code for anyone else who may be looking to do the same.
0
2961
by: Pawan Narula via DotNetMonster.com | last post by:
hi all, i'm using VB.NET and trying to code for contact management in a tree. all my contacts r saved in a text file and my C dll reads them one by one and sends to VB callback in a sync mode thread. so far so good. all contacts r added properly. now when another login adds me in his contact, i recv a subscription, so i popup a form and ask for accept/reject. this all happens in a separate thread. popup form gets opened and choice is...
3
16058
by: msnews.microsoft.com | last post by:
Hi i am using User32.dll in Visual stdio 2005. public static extern long SetActiveWindow(long hwnd); public static extern long keybd_event(byte bVk, byte bScan, long dwFlags,
5
1637
by: Lee | last post by:
(I also posted this query in Microsoft.Public.DotNet.Framework yesterday, but since I have received no responses, I am posting it here too.) Using Windows XP with all updates applied and Visual Studio 2.0. I am trying to develop some common error-handling of Windows API invocations that fail and am using MessageBeep as the API to test with. Given 1) the following Imports statement:
0
1570
by: Yong | last post by:
I have a COM DLL written in C++ which worked fine when called from VB6. But we have now moved to Visual Studio 2005 - .NET Framework v2 and Windows XP Pro. In total there are 4 methods in this DLL which I can call, 3 of which have no return paramters as arguments (ByRef), these work fine, its only the method that uses 2 passed in paramters (Long - ByRef) to return the the required data that causes an exception. So from my VB.NET program:...
2
1511
by: Gillard | last post by:
hello I get a dll with standard call in C ++ but I really do not know how to use it in VB anyone can help??? there is the declarations in cpp to use the functions #ifndef SFPDF_H #define SFPDF_H
6
2290
by: =?Utf-8?B?Sm9lbWFuYw==?= | last post by:
Hi, I'm trying to figure out the Callback method. I have a .dll that I call from a sub in my unmanaged code/calling program. That works just fine. But I'd like to have the .dll finish doing it's thing before returning to my calling program. Right now, with the code I've been testing with, the calling program goes to the .dll and then returns back to the calling program without letting the .dll do it's thing. Just having a hard time...
10
4546
by: Matthias | last post by:
Dear newsgroup. I want to write a template function which accepts either integer or floating point numbers. If a certain result is not a whole number and if the template parameter is an integer, it should return false, but it should work normally if the parameter is a float. To illustrate this, I attached a minimal example.
0
9619
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10102
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8933
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6712
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.