C++ templates interfaces using - c++

I found template interfaces very elegant, and trying implementing it faced problem that I can't solve. I hope you can shed some light on it for me.
I have class, for example, forge.h:
template<typename T> class Smelter;
template <typename T>
class Forge
{
long SmeltIt(vector<T>& ore)
{
long res;
Smelter<T> smelter;
for (const auto t : ore)
{
res += smelter.smelt(t);
}
return res;
}
};
With template class Smelter without any realization and template class Forge with realization.
Now, when I want to add class Iron, I need to create iron.h and implement Smelter to use it, this way iron.h:
#include "forge.h"
class Iron {};
template<>
class Smelter<Iron>
{
long smelt(const Iron& iron) { return 5; }
};
int main()
{
vector<Iron> ore;
Iron iron;
ore.push_back(iron);
ore.push_back(iron);
ore.push_back(iron);
Forge<Iron> forge;
cout << forge.SmeltIt(ore); //have to be 15
}
If all this stuff is in one header file, everything perfectly works. But if I create iron.h where I try to implement Smelter, compiler can't find template class Smelter. If I create copy of declaration for Smelter in both forge.h and iron.h, then they conflict with each other.
What is the best solution for that? It would be very useful if I would be able to realize my template interface in other files. Without this such template interfaces becomes ugly, for example, if forge.h is tools, wirely used between projects, and iron.h is my current specialization.
RESULT:
Everything works as expected, problem was outside of described question, in namespaces. All templates, even if it is possible to separate them between different files (that was question) - perfectly works. But they have to share same namespaces.

after fixing some minor issues, your code compiles fine (using clang 3.3) and produces the required result. here is the fixed code (in one file, but in the order of #include)
template<typename T> class Smelter;
template <typename T>
class Forge
{
public:
long SmeltIt(std::vector<T>& ore) // must be public; use std::
{
long res{}; // must be initialized (to 0)
Smelter<T> smelter;
for (const auto t : ore)
res += smelter.smelt(t);
return res;
}
};
class Iron {};
template<>
class Smelter<Iron>
{
public:
long smelt(const Iron& iron) // must be public
{ return 5; }
};
int main()
{
std::vector<Iron> ore; // std::
Iron iron;
ore.push_back(iron);
ore.push_back(iron);
ore.push_back(iron);
Forge<Iron> forge;
std::cout << forge.SmeltIt(ore) // have to be 15
<< std::endl;
}

Related

How to induce some template classes being united by one template?

I have some template classes. They are united by one namespace, and really they depends on each other's template parameter.
That is a good point for using #define T instead of template, and use in all classes, but client for those classes may want create some such pairs with different T, that is why I want to use templates.
But if I create just two separated classes with their own separated templates, I have good chance that client will make mistake and will put different values there. So, I would like to avoid it, if it is possible, to make set T once for pair of such classes and use both classes with it's value.
I would like to create something like that (just imagine):
template<int T>
namespace Sample
{
struct A
{
char _data[T];
}
struct B
{
void Get(A& a)
{
memcpy(b, a._data, T);
}
char b[T];
}
}
So, there are separated classes, but if one has parameter T = 50, then other have to work with same parameter. Best solution - template namespace, but C++ has no template namespaces.
Is it possible to make it somehow? Maybe I need any pattern?
I don't want to add something like:
char X1[T1 - T2 + 1];
char X2[T2 - T1 + 1];
Inside class B, to get error if T1 != T2 at compilation, I would like to find simple and beauty solution for that task, I believe it have to exist :-)
Use nested classes. Simply replace namespace with struct.
template<int T>
struct Sample {
struct A {
char _data[T];
};
struct B{
// ...
};
// You can have static methods that operate on types from
// the same template instance without specifying the type
static void foo(B& b) {
A a{0};
b.Get(a);
}
};
int main() {
Sample<2>::A a{0};
Sample<2>::B b;
b.Get(a);
}
Perhaps remove the constructor of Sample so no one tries to instantiate it.
I don't see how this is a problem. The following code already will not compile due to different values being used for the respective T parameters:
template <int T>
struct A
{
};
template <int T>
struct B
{
Get(A<T>& a) {}
};
int main()
{
A<5> a;
B<10> b;
b.Get(a); // cannot convert A<5> to A<10>&
}

non datatype template parameter, more specialization generated?

My Code is:
#include <iostream>
using namespace std;
template <typename T, int X>
class Test
{
private:
T container[X];
public:
void printSize();
};
template <typename T, int X>
void Test<T,X>::printSize()
{
cout <<"Container Size = "<<X <<endl;
}
int main()
{
cout << "Hello World!" << endl;
Test<int, 20> t;
Test<int, 30> t1;
t.printSize();
t1.printSize();
return 0;
}
Question:
How many specialization will get generated?.
If I understand correctly , it generates two specializations one is for <int, 20> and another is for <int, 30>. Kindly Correct if my understanding is wrong?
Is there any way to see/check the number of specializations generated by any reverse engineering?
There are not specializations here, only instantiations (this questions explains the difference). This code generates two instantiations of the class template Test.
1) yes, two instantiations will be generated by the compiler, but the linker might merge functions with identical generated code (using whole program optimization e.g.), which is a cute way to reduce code bloat.
2) see this question where it is explained how gcc can generate template instantiation output.
a) There are 2 instances of specialization get created in your example.
b)There is no builtin method to support number of specialization generated for a class.
If its your project you can add static count.
If you want you can write your own reference count mechanism for your class.
Increment static count in our constructor.
static int created = 0;
static int alive = 0;
class Test
{
counter()
{
created++;
alive++;
}
~counter()
{
created--;
}
//Rest of class
};

static if in plain c++?

Problem in short:
How could one implement static if functionality, proposed in c++11, in plain c++ ?
History and original problem:
Recently I came up with a problem like this. I need a class Sender with an interface like
class Sender
{
void sendMessage( ... );
void sendRequest( ... );
void sendFile( ... );
// lots of different send methods, not important actually
}
In some cases I will need to create a DoubleSender, i.e. an instance of this class, which would call its methods twice, i.e. when calling, let's say, a sendMessage(...) method, the same message has to be sent twice.
My solutions:
First approach:
Have an isDouble member, and in the end of each method call make a check
sendMessage(...) { ... if( isDouble ) { sendMessage( ... ); }
Well, I don't want this, because actually I will need double posting very recently, and this part of code in time-critical section will be 98% passive.
Second approach:
Inherit a class DoubleSender from Sender, and implement its methods like:
void DoubleSender::sendMessage( ... )
{
Sender::sendMessage(...);
Sender::sendMessage(...);
}
Well, this is acceptable, but takes much space of unpleasant code (really much, because there are lots of different send.. methods.
Third approach:
Imagine that I am using c++11 :). Then I can make this class generic and produce the necessary part of code according to tempalte argument using static if:
enum SenderType { Single, Double };
template<SenderType T>
class Sender
{
void sendMessage(...)
{
// do stuff
static if ( T == Single )
{
sendMessage(...);
}
}
};
This is shorter, easier to read than previous solutions, does not generate additional code and... it's c++11, which I unfortunately cannot use in my work.
So, here is where I came to my question - how can I implement static if analog in c++ ? Also, I would appreciate any other suggestions about how to solve my original problem.
Thanks in advance.
Quoting #JohannesSchaubLitb
with my static_if that works on gcc one can do it :)
in some limited fashion
(see also here)
This trick involves a specific GCC interpretation of the specs on Lambdas in C++11. As such, it will (likely) become a defect report against the standard. This will lead to the trick no longer working in more recent version of GCC (it already doesn't work in 4.7).
See the comment thread below for some more details from Johanness
http://ideone.com/KytVv:
#include <iostream>
namespace detail {
template<bool C>
struct call_if { template<typename F> void operator<<(F) { } };
template<>
struct call_if<true> {
template<typename F>
void operator<<(F f) { f(); }
};
}
#define static_if(cond) detail::call_if<cond>() << [&]
template<bool C, typename T>
void f(T t) {
static_if(C) {
t.foo();
};
}
int main() {
f<false>(42);
}
Why not make the send implementation a policy of the sender class and use CRTP:
template<class Derived>
class SingleSenderPolicy
{
public:
template< class memFunc >
void callWrapperImpl(memFunc f, ...)
{
static_cast<Derived *>(this)->f(...);
}
};
template< class Derived >
class DoubleSenderPolicy
{
public:
template< class memFunc >
void callWrapperImpl(memFunc f, ...)
{
static_cast<Derived *>(this)->f(...);
static_cast<Derived *>(this)->f(...);
}
};
template< class SendPolicy>
class Sender : public SendPolicy< Sender >
{
public:
void sendMessage( ... )
{
// call the policy to do the sending, passing in a member function that
// acutally performs the action
callWrapperImpl( &Sender::sendMessageImpl, ... );
}
void doSomethingElse( ... )
{
callWrapperImpl( &Sender::doSomethingElseImpl, ... );
}
protected:
void sendMessageImpl(... )
{
// Do the sending here
}
void doSomethingElseImpl(... )
{
// Do the sending here
}
};
The public sendXXX functions in you class simply forward to the call wrapper, passing in a member function that implements the real functionality. This member function will be called according to the SendPolicy of the class. CRTP saves the use of bind to wrap the arguments and this pointer up with the member function to call.
With one function it doesn't really cut down on the amount of code, but if you have a lot of calls it could help.
Note: This code is a skeleton to provide a possible solution, it has not been compiled.
Note: Sender<DoubleSenderPolicy> and Sender<SingleSenderPolicy> are completely different types and do not share a dynamic inheritance relationship.
Most compilers do constant folding and dead code removal, so if you write a regular if statement like this:
enum SenderType { Single, Double };
template<SenderType T>
class Sender
{
void sendMessage(...)
{
// do stuff
if ( T == Single )
{
sendMessage(...);
}
}
};
The if branch will get removed when the code is generated.
The need for static if is when the statements would cause a compiler error. So say you had something like this(its somewhat psuedo code):
static if (it == random_access_iterator)
{
it += n;
}
Since you can't call += on non-random access iterators, then the code would always fail to compile with a regular if statement, even with dead code removal. Because the compiler still will check the syntax for before removing the code. When using static if the compiler will skip checking the syntax if the condition is not true.
std::string a("hello world");
// bool a = true;
if(std::is_same<std::string, decltype(a)>::value) {
std::string &la = *(std::string*)&a;
std::cout << "std::string " << la.c_str() << std::endl;
} else {
bool &la = *(bool*)&a;
std::cout << "other type" << std::endl;
}

Checking a member exists, possibly in a base class, VS2005/08 version

In Checking a member exists, possibly in a base class, C++11 version, we developed a C++11 version of the classical member-checking type-trait from SFINAE to check for inherited member functions that also works with C++11 final classes, but uses C++11 features (namely, decltype), too:
template<typename T>
class has_resize_method {
struct Yes { char unused[1]; };
struct No { char unused[2]; };
static_assert(sizeof(Yes) != sizeof(No));
template<class C>
static decltype(std::declval<C>().resize(10), Yes()) test(int);
template<class C>
static No test(...);
public:
static const bool value = (sizeof(test<T>(0)) == sizeof(Yes));
};
MSVC has had final as a non-standard extension named sealed since VS2005, but decltype has only been added in VS2010. That leaves VS2005 and 2008 where a class that is marked as sealed still breaks the classical type-trait and the C++11 version cannot be used.
So, is there a way to formulate has_resize_method such that it works on VC2005/08 sealed classes, too?
Obviously, just as using C++11-only features to work around a C++11-only problem (final) is fine, so would be using VS-only extensions to work around the VS2005/08-only problem of sealed classes, but if there's a solution that works for all three sets of compilers {C++11,{VS2005,VS2008},all others}, that would be cool, but probably too much to ask for :)
I was able to come up with a solution that works in all major compilers. Sadly, there is a preprocessor check for MSVC because it complains about the solution for other compilers. The main difference is that MSVC does not accept function pointers inside sizeof() and conversely, GCC does not seem to accept (&C::resize == 0) in the check. Clang happily accepts both.
#include <iostream>
class Base {
public:
void resize(int, int, int) { }
};
class Derived : public Base {
};
class Unrelated { };
template<typename T>
class has_resize_method {
struct Yes { char unused[1]; };
struct No { char unused[2]; };
#ifdef _MSC_VER
template <class C>
static Yes test(char (*)[(&C::resize == 0) + 1]);
#else
template <class C>
static Yes test(char (*)[sizeof(&C::resize) + 1]);
#endif
template<class C>
static No test(...);
public:
static const bool value = (sizeof(test<T>(0)) == sizeof(Yes));
};
int main() {
std::cout << (has_resize_method<Base>::value ? "Base has method resize" : "Base has NO method resize") << std::endl;
std::cout << (has_resize_method<Derived>::value ? "Derived has method resize" : "Derived has NO method resize") << std::endl;
std::cout << (has_resize_method<Unrelated>::value ? "Unrelated has method resize" : "Unrelated has NO method resize") << std::endl;
return 0;
}
Output:
Base has method resize
Derived has method resize
Unrelated has NO method resize
Tested on GCC 4.5.3, GCC 4.3.4, Clang 3.0, Visual C++ 2008 and Visual C++ 2010. I don't have access to Visual C++ 2005 but I think it will work there, too. It also compiles on Comeau Online but I cannot guarantee it produces a correct output there.
Works with both final and __sealed classes.
Note though that it checks not only for member functions but for member pointers in general. You might want to add additional checks such as boost::is_member_function_pointer if this behavior is unwanted. Similarly, you might want to add checks for number of arguments/argument types/result types - again, boost will be very helpful here, esp. boost type decomposition.
MSVC has a special statement __if_exists since vs2005. MSDN Link here. You can use it to check the member function name directly. And then check the signature. Following is a simple foo detection example:
template <typename T, typename U>
int8_t FooCheck( void(T::*)(U) )
{
return 0;
}
template <typename T>
int16_t FooCheck( void(T::*)(double))
{
return 0;
}
template <typename T>
int32_t FooCheck(void(T::*)(int))
{
return 0;
}
template <typename T>
class Detector
{
public:
__if_exists(T::foo)
{
enum
{
value = sizeof(FooCheck(&T::foo))
};
}
__if_not_exists(T::foo)
{
enum
{
value = 0
};
}
};
std::cout << Detector<Class>::value << std::endl;

Class member functions instantiated by traits [policies, actually]

I am reluctant to say I can't figure this out, but I can't figure this out. I've googled and searched Stack Overflow, and come up empty.
The abstract, and possibly overly vague form of the question is, how can I use the traits-pattern to instantiate member functions? [Update: I used the wrong term here. It should be "policies" rather than "traits." Traits describe existing classes. Policies prescribe synthetic classes.] The question came up while modernizing a set of multivariate function optimizers that I wrote more than 10 years ago.
The optimizers all operate by selecting a straight-line path through the parameter space away from the current best point (the "update"), then finding a better point on that line (the "line search"), then testing for the "done" condition, and if not done, iterating.
There are different methods for doing the update, the line-search, and conceivably for the done test, and other things. Mix and match. Different update formulae require different state-variable data. For example, the LMQN update requires a vector, and the BFGS update requires a matrix. If evaluating gradients is cheap, the line-search should do so. If not, it should use function evaluations only. Some methods require more accurate line-searches than others. Those are just some examples.
The original version instantiates several of the combinations by means of virtual functions. Some traits are selected by setting mode bits that are tested at runtime. Yuck. It would be trivial to define the traits with #define's and the member functions with #ifdef's and macros. But that's so twenty years ago. It bugs me that I cannot figure out a whiz-bang modern way.
If there were only one trait that varied, I could use the curiously recurring template pattern. But I see no way to extend that to arbitrary combinations of traits.
I tried doing it using boost::enable_if, etc.. The specialized state information was easy. I managed to get the functions done, but only by resorting to non-friend external functions that have the this-pointer as a parameter. I never even figured out how to make the functions friends, much less member functions. The compiler (VC++ 2008) always complained that things didn't match. I would yell, "SFINAE, you moron!" but the moron is probably me.
Perhaps tag-dispatch is the key. I haven't gotten very deeply into that.
Surely it's possible, right? If so, what is best practice?
UPDATE: Here's another try at explaining it. I want the user to be able to fill out an order (manifest) for a custom optimizer, something like ordering off of a Chinese menu - one from column A, one from column B, etc.. Waiter, from column A (updaters), I'll have the BFGS update with Cholesky-decompositon sauce. From column B (line-searchers), I'll have the cubic interpolation line-search with an eta of 0.4 and a rho of 1e-4, please. Etc...
UPDATE: Okay, okay. Here's the playing-around that I've done. I offer it reluctantly, because I suspect it's a completely wrong-headed approach. It runs okay under vc++ 2008.
#include <boost/utility.hpp>
#include <boost/type_traits/integral_constant.hpp>
namespace dj {
struct CBFGS {
void bar() {printf("CBFGS::bar %d\n", data);}
CBFGS(): data(1234){}
int data;
};
template<class T>
struct is_CBFGS: boost::false_type{};
template<>
struct is_CBFGS<CBFGS>: boost::true_type{};
struct LMQN {LMQN(): data(54.321){}
void bar() {printf("LMQN::bar %lf\n", data);}
double data;
};
template<class T>
struct is_LMQN: boost::false_type{};
template<>
struct is_LMQN<LMQN> : boost::true_type{};
// "Order form"
struct default_optimizer_traits {
typedef CBFGS update_type; // Selection from column A - updaters
};
template<class traits> class Optimizer;
template<class traits>
void foo(typename boost::enable_if<is_LMQN<typename traits::update_type>,
Optimizer<traits> >::type& self)
{
printf(" LMQN %lf\n", self.data);
}
template<class traits>
void foo(typename boost::enable_if<is_CBFGS<typename traits::update_type>,
Optimizer<traits> >::type& self)
{
printf("CBFGS %d\n", self.data);
}
template<class traits = default_optimizer_traits>
class Optimizer{
friend typename traits::update_type;
//friend void dj::foo<traits>(typename Optimizer<traits> & self); // How?
public:
//void foo(void); // How???
void foo() {
dj::foo<traits>(*this);
}
void bar() {
data.bar();
}
//protected: // How?
typedef typename traits::update_type update_type;
update_type data;
};
} // namespace dj
int main() {
dj::Optimizer<> opt;
opt.foo();
opt.bar();
std::getchar();
return 0;
}
A simple solution might be to just use tag-based forwarding, e.g. something like this:
template<class traits>
void foo(Optimizer<traits>& self, const LMQN&) {
printf(" LMQN %lf\n", self.data.data);
}
template<class traits>
void foo(Optimizer<traits>& self, const CBFGS&) {
printf("CBFGS %d\n", self.data.data);
}
template<class traits = default_optimizer_traits>
class Optimizer {
friend class traits::update_type;
friend void dj::foo<traits>(Optimizer<traits>& self,
const typename traits::update_type&);
public:
void foo() {
dj::foo<traits>(*this, typename traits::update_type());
}
void bar() {
data.bar();
}
protected:
typedef typename traits::update_type update_type;
update_type data;
};
Or if you want to conveniently group several functions together for different traits, maybe something like this:
template<class traits, class updater=typename traits::update_type>
struct OptimizerImpl;
template<class traits>
struct OptimizerImpl<traits, LMQN> {
static void foo(Optimizer<traits>& self) {
printf(" LMQN %lf\n", self.data.data);
}
};
template<class traits>
struct OptimizerImpl<traits, CBFGS> {
static void foo(Optimizer<traits>& self) {
printf("CBFGS %d\n", self.data.data);
}
};
template<class traits = default_optimizer_traits>
class Optimizer{
friend class traits::update_type;
friend struct OptimizerImpl<traits>;
public:
void foo() {
OptimizerImpl<traits>::foo(*this);
}
// ...
};
I think template specialization is a step in the right direction. This doesn't work with functions so I switched to classes. I changed it so it modifies the data. I'm not so sold on the protected members and making friends. Protected members without inheritance is a smell. Make it public or provide accessors and make it private.
template <typename>
struct foo;
template <>
struct foo<LMQN>
{
template <typename OptimizerType>
void func(OptimizerType& that)
{
printf(" LMQN %lf\n", that.data.data);
that.data.data = 3.14;
}
};
template <>
struct foo<CBFGS>
{
template <typename OptimizerType>
void func(OptimizerType& that)
{
printf(" CBFGS %lf\n", that.data.data);
}
};
template<class traits = default_optimizer_traits>
class Optimizer{
public:
typedef typename traits::update_type update_type;
void foo() {
dj::foo<typename traits::update_type>().func(*this);
}
void bar() {
data.bar();
}
update_type data;
};
It would be trivial to define the traits with #define's and the member functions with #ifdef's and macros. But that's so twenty years ago.
Although it may be worth learning new methods, macros are often the simplest way to do things and shouldn't be discarded as a tool just because they're "old". If you look at the MPL in boost and the book on TMP you'll find much use of the preprocessor.
Here's what I (the OP) came up with. Can you make it cooler?
The main Optimizer template class inherits policy-implementation classes. It gives those classes access to the Optimizer's protected members that they require. Another Optimizer template class splits the manifest into its constituent parts and instantiates the main Optimizer template.
#include <iostream>
#include <cstdio>
using std::cout;
using std::endl;
namespace dj {
// An updater.
struct CBFGS {
CBFGS(int &protect_)
: protect(protect_)
{}
void update () {
cout << "CBFGS " << protect << endl;
}
// Peek at optimizer's protected data
int &protect;
};
// Another updater
struct LMQN {
LMQN(int &protect_)
: protect(protect_)
{}
void update () {
cout << "LMQN " << protect << endl;
}
// Peek at optimizer's protected data
int &protect;
};
// A line-searcher
struct cubic_line_search {
cubic_line_search (int &protect2_)
: protect2(protect2_)
{}
void line_search() {
cout << "cubic_line_search " << protect2 << endl;
}
// Peek at optimizer's protected data
int &protect2;
};
struct default_search_policies {
typedef CBFGS update_type;
typedef cubic_line_search line_search_type;
};
template<class Update, class LineSearch>
class Opt_base: Update, LineSearch
{
public:
Opt_base()
: protect(987654321)
, protect2(123456789)
, Update(protect)
, LineSearch(protect2)
{}
void minimize() {
update();
line_search();
}
protected:
int protect;
int protect2;
};
template<class Search_Policies=default_search_policies>
class Optimizer:
public Opt_base<typename Search_Policies::update_type
, typename Search_Policies::line_search_type
>
{};
} // namespace dj
int main() {
dj::Optimizer<> opt; // Use default search policies
opt.minimize();
struct my_search_policies {
typedef dj::LMQN update_type;
typedef dj::cubic_line_search line_search_type;
};
dj::Optimizer<my_search_policies> opt2;
opt2.minimize();
std::getchar();
return 0;
}
Your use of enable_if is somewhat strange. I've seen it used it only 2 ways:
in place of the return type
as a supplementary parameter (defaulted)
Using it for a real parameter might cause the havoc.
Anyway, it's definitely possible to use it for member functions:
template<class traits = default_optimizer_traits>
class Optimizer{
typedef typename traits::update_type update_type;
public:
typename boost::enable_if< is_LQMN<update_type> >::type
foo()
{
// printf is unsafe, prefer the C++ way ;)
std::cout << "LQMN: " << data << std::endl;
}
typename boost::enable_if< is_CBFGS<update_type> >::type
foo()
{
std::cout << "CBFGS: " << data << std::endl;
}
private:
update_type data;
};
Note that by default enable_if returns void, which is eminently suitable as a return type in most cases. The "parameter" syntax is normally reserved for the constructor cases, because you don't have a return type at your disposal then, but in general prefer to use the return type so that it does not meddle with overload resolution.
EDIT:
The previous solution does not work, as noted in the comments. I could not find any alternative using enable_if, only the "simple" overload way:
namespace detail
{
void foo_impl(const LMQN& data)
{
std::cout << "LMQN: " << data.data << std::endl;
}
void foo_impl(const CBFGS& data)
{
std::cout << "CBFGS: " << data.data << std::endl;
}
} // namespace detail
template<class traits = default_optimizer_traits>
class Optimizer{
typedef typename traits::update_type update_type;
public:
void foo() { detail::foo_impl(data); }
private:
update_type data;
};
It's not enable_if but it does the job without exposing Optimizer internals to everyone. KISS ?