Generate a unique template instance for use of template - c++

Does anyone know if it's possible to generate a unique template instance (I think that's the word), for every use, even if the types are matching?
My thought was to use some type of compile time counter? Like
constexpr int next_count()
{
// what do I do here?
}
template
struct foo
{
...
};
template
auto make_foo(T val)
{
return foo(val);
}
Any help on this would be appreciated. If it doesn't make sense, that's fine to say as well.

You could pass an extra template parameter to the make_foo function, and add an extra template parameter to the original foo class (they would be ints), and choose a different value for each time the function is called. If you want it to increment automatically, the best thing I can think of is using __LINE__. Then you can #define MAKE_FOO(targs, val) make_foo<targs, __LINE__>(val). Add more targs as necessary. Don't forget to wrap foo in an anonymous namespace if you really want each instance to be a separate class (if this is going to be in a header file).

Related

multiple functions with same name but different argument types as template parameter

I'm using xsd to create c++ code from a xml schema file. For a xml type multiple functions are created (for serialization etc).
If the type is called XmlType multiple functions of the following form are created:
XmlType XmlType_(const XmlType& a, const string& b)
string XmlType_(const XmlType& a)
...
This are normal functions and not members of XmlType and they all have the same name.
For XmlType2 the functions would be called XmlType2_.
I would like to write a utility template class for all the different xml types of my xml scheme. The different functions are going to be called insight this class. What I have so far is something like this:
template<typename T>
using TFunc1 = T (*)(const T&, const string&);
template<typename T>
using TFunc2 = string (*)(const T&);
template<typename T, TFunc1<T> func2, TFunc2<T> func2>
class XmlUtil {
...
};
When create an instance of the XmlUtil class if have to do it like this:
XmlUtil<XmlType, XmlType_, XmlType_> util;
This feels a bit redundant and gets worse, when I have to pass more functions as parameters.
I would like to use the util class like this:
XmlUtil<XmlType, XmlType_> util;
or even better like this
XmlUtil<XmlType> util;
The only way I can think of is to somehow use define, but it doesn't feel right.
Is there an other way to do this?
EDIT:
I'm using a define now:
#define TRPL(name) name, name ## _, name ## _
...
XmlUtil<TRPL(XmlType)> util;
I'll edit this, if I find something better (maybe override sets like Yakk suggested in his answer).
This:
XmlUtil<XmlType> util;
is impossible because there is no way to get from XmlType to XmlType_. Their relationship is discarded after the automatic code generator.
However this:
XmlUtil<XmlType_> util;
may be possible. You can deduce the function type of XmlType_ and then use the deduced return type which will be XmlType. I believe there are standard library function for this purpose.
As for the two different overloads, that may be trickier. I do not think that you can pass a function overload set as a template parameter, the resolution is done on the template argument in the context of the template parameter to one function. I don't think there is a way to defer this action without using the preprocessor.
So I would argue that you should use a #define. It is better than nothing.
This looks like a job for override sets.
static struct foo_override_set_type {
template<typename... Args>
auto operator()( Args...&& args ) const
->
decltype( foo( std::forward<Args>(args)... ) )
{ return ( foo( std::forward<Args>(args)... ) ); }
template<typename T>
operator T() { return foo; }
} foo_override_set;
Objects of type foo_override_set_type represent the entire override set of foo. Calling them with operator() does an override set lookup on foo and calls the resulting function. Casting them to a function pointer does the same thing as casting the token foo to a function pointer (or other value).
Your code generation can auto-generate such override set types. It can also make a traits class that maps from your type XmlType to the override set of XmlType_ functions via specialization.
Then, your XmlUtil<XmlType> can access the override set of XmlType_ via that traits class. It first instantiates the override set variable, then invokes () on it.
As an aside, #Xeo has a proposal to make creating such objects as easy as typing []XmlType_ in C++1y or C++1z.
Default template arguments in the class definition?
Like
template<typename T, TFunc1<T> func1 = XmlType_, TFunc2<T> func2 = XmlType_>
class XmlUtil {
// ...
};
You can use a trait class like this
template <typename T>
struct Trait{
typedef T type;
typedef T (*func1)(const T&, const string&);
typedef string (*func2)(const T&);
};
and make the class XmlUtil have one template parameter (let's name it Trait) and use Trait::type, Trait::func1 and Trait::func2. See here for full usage.
In the example, the type of XmlUtil goes like:
XmlUtil<Trait<XmlType> >
I've done it this way since I don't know well your problem. It might be the case that you can just define the Trait class right into XmlUtil and use
XmlUtil<XmlType>
Other variations are possible, it just depend on what you need.
You can read a very brief introduction to trait classes here. If you want to read more about this topic I suggest you Modern C++ (Alexandrescu).
I am not sure I fully understand what you are asking. The common approach for serialization and deserialization would be to create a factory (abstract factory) and resolve the construction of the objects dynamically. Note that this can be improved for complex structures, where the code generator can create member functions to extract the exact type of each one of the members.
But again, I don't fully understand what you are really trying to do... As a recommendation I believe it would help if you provided more of a description of the problem to solve, as the question focuses on how to make your solution work, and that implicitly discards other approaches that might be better designs.

Is there a way to use a default template argument without having to use <> in C++?

I have a struct being used somewhere which is declared as:
struct Foo
{
someArray[64];
//...other stuff
};
It is used extensively in many places, and I would like to change it to this:
template <size_t N = 64>
struct Foo
{
someArray[N];
//...other stuff
};
because there is one place (well four to be exact) where this struct needs to be used with a 128 byte array for correctness, but the penalty it introduces for ALL the other uses is not worth paying. In providing a default template argument I was hoping it would go through transparently, except for those in the know-how who need a wider internal array which would then declare Foo<128>. Unfortunately, it seems to force every use of it to say Foo<>. Is there a way around this?
You cannot omit the angular brackets when instantiating a class template.
However, you can give a different name to your Foo class template (say, FooN) and then provide a type alias such as:
typedef FooN<> Foo;
This way, clients who were using the original, non-template version of Foo won't have to be changed, and clients that need the flexibility of overriding the default N can use the generic class template:
FooN<128> obj;
To answer the question first: No there isn't a way to use it without <>. However that doesn't mean you can't do something else to keep your codebase intact.
The easiest solution is to rename templated variant to something else and provide a Typedef for the name Foo:
template <size_t N = 64>
struct GenericFoo
{
someArray[N];
//...other stuff
};
typedef GenericFoo<64> Foo;
This way you can keep using Foo in all the other instances and have the option of using GenericFoo<Whatever> when you need fine grained control.
namespace generic
{
template <int N> class Foo {};
}
// user code
typedef generic::Foo<64> Foo; // common users
// OR
using generic::Foo; // rare users

Template and is_same() doesn't work?

if (std::is_same<T, float>::value)
{
float a;
somefunc_float(x,len,&a);
}
The above code is from a template, which accept a pointer x that can be a pointer of some primitive data type (e.g. x being double *, float * or int *), and somefunc_float is from a lib, can only accept one specific data type of x (float * in the above example), the compiler always give me error, telling me the input data type (x) is incorrect, as if the expressionstd::is_same<T, float>::value doest work at all?
The description of the problem is not completely clear, but I think I understand what you are trying to do: You are enclosing a block of code inside the template function with a test that can be performed at compile time, and expect that the compiler will discard that block and not compile it.
Templates don't work like that. When a template is instantiated, the whole template is checked and compiled and the code must be correct before the optimizer can discard blocks of code (which it probably would in this case).
The common approach to obtain that behavior is providing multiple implementations of the template (or non-template overloads) that are called with different types. The compiler will dispatch at the place of call to the appropriate implementation and will then ignore the rest.
There are proposals for static if functionality in a future version of C++ (probably C++17) that would support what you are trying to do.
Types are determined statically, and all template code that is instantiated must compile, i.e. make sense. The content of an if statement must make sense even if the condition is false.
Try something like this:
template <typename T> execute_if_float(T) { }
execute_if_float(float x) { somefunc_float(x); }
template <typename T> void myCode(T x)
{
// ...
execute_if_float(x);
// ...
}

C++ generate function body containing switch/map from template argument types

I wish to modify an existing templated class. The class's template arguments are (semi) variable and I would like to use them to generate a conditional/switch/map like function body.
My compiler does not support variadic templates so the (boost) preprocessor is currently used to generate the existing class:
template <typename item0, typename item1, typename item2 ..., typename itemN>
struct myclass { /*various operations*/ };
A new function func is required that will query variables at run-time and return an object of a that is one of the template arguments.
Example:
template <typename item0, typename item1, typename item2 ...>
struct my_class {
//...various operations
//automatic generatation possible?
std::string * func()
{
string s;
while(data) {
switch (data[0])
{
case item0::id:
s += item0::get_name();
case item1::id:
s += item1::get_name();
//... for each template arguemnt typename where typename is no void
}
}
return s;
}
};
typedef my_class<a, b, c> class_one;
typedef my_class<d, e, f> class_two;
typedef my_class<a, b, c, x, y, z> class_three;
int main()
{
...
class_one test;
test.func();
...
}
I would like to generate the contents of func() because the number of items will be numerous, and the number of types of "myclass" will be even higher.
Can someone give me an idea of how any techniques that could accomplished this?
I already have a dependency on boost. My compiler is reasonably new (but does not support variadic templates). I would prefer not to take any new dependencies or introduce more complexity than necesssary.
I've written code like this before, so I can tell you it is possible. (It was for commercial, closed-source work, so I'm afraid I can't show you the code). You can find a really good example of how to do this in the Boost.Variant library, in particular http://svn.boost.org/svn/boost/trunk/boost/variant/detail/visitation_impl.hpp . The code is very dense and advanced C++, so it might take a day or two to understand it thoroughly.
A quick summary: the boost::variant class template works like a union with an int storing which member of the union is valid. The "visitation" feature lets you supply a function object with an overloaded operator() that can take any of the possible members of the union, and it generates a switch statement that accesses the appropriate member and calls the right operator() overload on it. If you are already finding this complicated to follow, or you don't know about Boost.MPL yet, I suggest you stop reading here, read the Boost.Variant documentation, and then rewrite your class to be able to use that: the clever guys at Boost have already done the work for you. It's header-only, so if you're already using Boost there's no new dependency for you.
This file is in charge of generating the switch statement. In short, it has two alternative implementations. The first one (lines 72-90) uses a recursive template visitation_impl_step that works like the factorial function you might have seen as a template meta-programming example. The unspecialized template recursively calls the next one in the list (typename mpl::next<Iter>::type). The resulting code, once all the templates are expanded out, looks a bit like a series of functions function0, function1, &c. like this:
result_type functionN(variant vnt, visitor vr) {
if (v.which == N)
return vr(static_cast<Nth type>(vnt.value));
else
functionN-1(vnt, vr);
}
The second implementation (lines 193-285) uses the Boost.PP preprocessor magic library to generate a switch statement just like the one you want, with as many cases as a boost::variant can possibly have. The body of each case is a call to a template function (lines 120-185) which generates a call to the visitor on the Nth type. Most of the complexity in this implementation comes from having to worry about backing up the value inside the variant in order to preserve the strong exception guarantee if the visitor or any involved constructor throws.
Even if you decide to do it another way, I recommend reading and understanding the Boost.Variant source code, as a learning exercise. It will redefine your ideas of what is possible (and what is sensible) in C++!
Compiler will be able to generate code using exact template definition. There is no way to force compiler to generate additional cases in switch statement or additional iterations of loops depending on template parameters.
If you want to perform perform some action on instance of each type specified in template parameters you have to implement recursive template function. Please refer to this question for details.

Conventional way for calling a template function

struct A
{
template <class U>
void f(U)
{
}
};
template <class T>
void f(T t)
{
A a;
a.template f<int>(t);
a.template f<>(t);
a.f<int>(t);
a.f<>(t);
a.f(t);
}
At least under MSVC2010 the above code compile fine.
Among all the manners to call A.f is there any preferentials way to do this?
Is there any differences ?
Well, a has type A, which is not a dependent type in this context. So the template keyword is not needed and only serves to obfuscate the code -- don't use it.
The version that invokes a template without supplying any arguments, again does nothing to change behavior and only makes the code less readable -- don't use it either.
Between the two remaining candidates, a.f(t) and a.f<int>(t), use the first in most cases, and the second if the compiler fails to deduce the type.
The last one seems easiest to write.
Otherwise there are no differences, unless you have to disambiguate between several f's.
No differences at all. If you don't have any reason to provide type information to the function, the last one is the best. But you may want your function to process arguments as if they are of the specified type, only then, should you need <>. For example
T Divide(T a, T b)
{
return a/b;
}
If you call Divide(5,2), you get 2. Only cases like this, should you specify type:
Divide<float>(5,2);
It returns 2.5.

Resources