Suppose I have a template class, which depending on a template parameter, may or may not have a member int x.
This can be realized by inheriting from a base template class, which for some specialization has a member int x.
Example code:
#include <iostream>
template <bool present>
struct base;
template <>
struct base<true> { int x; };
template <bool present>
struct base { };
template <bool activate>
struct A : public base<activate> {
void print() const;
};
template <bool activate>
void A<activate>::print() const
{
if constexpr (activate) {
std::cout << "x = " << this->x << std::endl;
} else {
std::cout << "nothing" << std::endl;
}
}
int main()
{
A<true> a;
a.print();
A<false> b;
b.print();
return 0;
}
In the code above A<true> contains a member int x, inherited from base<true>, whereas A<false> does not contain it.
Now, since x is a dependent name, in order to access it, I need to use this->x or base<true>::x. This can be somewhat burdersome to use it every time, so the common solution is to employ a using directive like
using base<true>::x;
inside the definition of A. But, of course, this makes sense only when activate=true.
Is it possible, perhaps with a macro, to add using base<true>::x in the definition of A, only when a condition (here activate=true) is satisfied?
It's a common issue to have optionally present members. If you're okay with multiple inheritance and some hacking, you can do this via a static empty variable in another base class:
struct Nothing {};
struct StaticNothing {
static Nothing x;
};
template <bool activate>
struct A : public base<activate>, StaticNothing {
using std::conditional_t<activate, base<true>, StaticNothing>::x;
void print() const;
};
Demo
Note that std::conditional_t<> decides which base x comes from. The benefit of this method is, you can always assume that there's an x member (either static or non-static), so you can take the address of it, etc.
another placeholder option is use a function, with the benefit that one can delete it to prevent unwanted access.
template <bool present>
struct base { constexpr void x()=delete; };
template <>
struct base<true> { int x = 0; };
template <bool activate>
struct A : public base<activate> {
using base<activate>::x;
void print() const{
auto&& p = x; // fail for A<false>::print
}
};
base on the comment of #Jarod42, but use anonymous class (optional) and inline variable to make sure it compiles without extra definitions. (regarding to OP's this comment)
template <bool present>
struct base { constexpr static struct{} x = {}; };
template <>
struct base<true> { int x = 0; };
template <bool activate>
struct A : public base<activate> {
using base<activate>::x;
void print() const;
};
Related
Is it possible to create a class template with a member function definition only if the object created is of a specific type?
I've created a template class I will use for storing either int or doubles, but for doubles I would like to be able to set precision too (objects created with myclass < double> should have this functionality, but for myclass< int> there is no need for that to be present at all).
I know I can use a base class template, and create new classes "myInt", "myDouble" using that and implement the functionality only in the myDouble class, but I think it would be cleaner to define the functionality (both the function and a member variable) for doubles in the class template, if that's possible and preferable?
Let's add an example to show what I want to do:
#include <iostream>
#include <iomanip>
class commonBase{
public:
void setState(int state);
virtual void print() = 0;
private:
int _my_state;
};
template <typename T>
class generalObject : public commonBase {
public:
void value(T value);
void print(){ std::cout << "My value: " << _my_value << std::endl; }
private:
T _my_value;
};
template <typename T>
void generalObject<T>::value(T value){
_my_value = value;
}
// Is there any way do specialize only only whats different from the generalObject template?
// Here I thought I could specialize the case where a generalObject is created of <double>, but
// when I do, nothing is derived from generalObject (or at least not visible as far as I can tell)
template<>
class generalObject<double>{
public:
void setPrecision(int precision){ _my_precision = precision; }
// here I would like a special implementation of print(), which overrides the print() in generalObject
// and instead also prints according to the precision set when the object is of <double> type.
// Row below an example which doesn't work (compiler error, _my_value undefined)
void print(){ std::cout << "My value: " << std::setprecision(_my_precision) << _my_value << std::endl; }
private:
int _my_precision;
};
int main(int argc, char* argv[]){
generalObject<int> o1;
o1.value(1);
o1.print();
o1.setState(1); //inherited from the commonBase
generalObject<double> o2;
o2.setPrecision(2);
o2.value(2); //here value isn't available (compile error)
o2.print();
o2.setState(123); //also isn't available (compile error)
}
Sure.
template <typename T> class Poly;
void set_precision(Poly<double>* self, int a) {};
If you really want dot notation you can then add:
template <typename T> class Poly {
public: void set_precision(int a){::set_precision(this,a);}
...
However I think you should think about what you're trying to accomplish. If MyInt and MyDouble have different fields and different methods and different implementations, they should probably be different classes.
This can be solved using template specialization.
We first define a common template...
template< typename T >
struct myclass
{
// common stuff
};
... and specialize that for double:
template<>
struct myclass<double>
{
int precision = 10;
void setprecision( int p ){ precision = p; }
};
Now the setprecision() method can only be called for myclass<double>. The compiler will complain if we try to call it for anything else, like myclass<int>.
int main()
{
myclass<double> d;
d.setprecision( 42 ); // compiles
myclass<int> i;
i.setprecision( 42 ); // fails to compile, as expected
}
Demo.
The basic way to have a member function of a class template exist only for some template parameters is to create a specialization of the class template for those template parameters.
template<typename T>class X{
// general definition
};
template<>class X<double>{
// double-specific definition
};
The downside of this is that the specialization will need to duplicate anything that is common. One way to address this is to move the common things out to a base class template:
template<typename T>class Xcommon{
// common stuff
};
template<typename T>class X: public Xcommon<T>{
// general definition
};
template<>class X<double>: public Xcommon<double>{
// double-specific definition
};
Alternatively, you can do it the other way: put the common stuff in the derived class, and the extras in the base, and specialize the base:
template<typename T>class Xextras{
// empty by default
};
template<typename T>class X: public Xextras<T>{
// common definition
};
template<>class Xextras<double>{
// double-specific definition
};
Either way can work; which is better depends on the details.
Both these methods work for data members and member functions.
Alternatively, you can use enable_if to mean that member functions are not selected by overload resolution if the template parameter doesn't meet a required condition. This requires that the member function is itself a template.
template<typename T>class X{
template<typename U=T> // make it a template,
std::enable_if<std::is_same_v<U,double>> double_specific_function(){
// do stuff
}
};
I wouldn't recommend this option unless there is no other choice.
If the question is about a member function, then here is one of the ways to do it without class template specialization:
#include <iostream>
#include <type_traits>
template <typename T>
struct Type {
template <typename U = T,
typename = typename std::enable_if<std::is_same<U, double>::value>::type>
void only_for_double() {
std::cout << "a doubling" << std::endl;
}
};
int main() {
Type<int> n;
Type<double> d;
// n.only_for_double(); // does not compile.
d.only_for_double();
}
Example on ideone.com
If you require a data-member presence based on the template parameter, you will have to do some kind of specialization, in which case it is, probably, simpler to put the function into corresponding specialization.
EDIT: After OP made his question more specific
Here is one way to do it without extra class and getting rid of virtual functions. Hope it helps.
#include <iostream>
#include <iomanip>
template <typename T, typename Derived = void>
class commonBase {
public:
void setState(int state) {
_my_state = state;
}
void value(T value) {
_my_value = value;
}
template <typename U = Derived,
typename std::enable_if<std::is_same<U, void>::value,
void * >::type = nullptr>
void print() const {
std::cout << "My value: " << _my_value << std::endl;
}
template <typename U = Derived,
typename std::enable_if<!std::is_same<U, void>::value,
void * >::type = nullptr>
void print() const {
static_cast<Derived const *>(this)->_print();
}
protected:
T _my_value;
int _my_state;
};
template <typename T>
class generalObject : public commonBase<T> {
};
template<>
class generalObject<double> : public commonBase<double, generalObject<double>> {
private:
friend commonBase<double, generalObject<double>>;
void _print() const {
std::cout << "My value: " << std::setprecision(_my_precision) <<
_my_value << std::endl;
}
public:
void setPrecision(int precision){ _my_precision = precision; }
private:
int _my_precision;
};
int main(){
generalObject<int> o1;
o1.value(1);
o1.print();
o1.setState(1);
generalObject<double> o2;
o2.setPrecision(2);
o2.value(1.234);
o2.print();
o2.setState(123);
}
Same code on ideone.com
I'm currently playing around with templates in C++ and got stuck with template template parameters.
Lets say I have the following classes:
template<typename T>
struct MyInterface
{
virtual T Foo() = 0;
}
class MyImpl : public MyInterface<int>
{
public:
int Foo() { /*...*/ }
};
template< template<typename T> typename ImplType>
class MyHub
{
public:
static T Foo()
{
ImplType i;
return i.Foo();
}
private:
MyHub() { }
~MyHub() { }
};
In essence I would like to have a static class like MyHub that accepts an implementation of MyInterface and provides certain static methods to use them like static T Foo().
Then I tried to use MyHub:
int main()
{
int i = MyHub<MyImpl>::Foo();
return 0;
}
Unfortunately I always end up getting an error saying that the type T (of static T Foo() in MyHub) does not name a type.
I would expect that it works because
the template parameter of the template parameter Impl is named T
MyHub is a templated class with one template parameter and contains a method Foo
So far I couldn't find a solution for this after digging through documentations and google results so I hope some of you can help me.
You can use typedefs. Also, since your implementation classes are not template class, there is no need for template template parameters.
#include <iostream>
#include <string>
template<typename T>
struct MyInterface
{
virtual T Foo() = 0;
typedef T Type;
};
class MyIntImpl : public MyInterface<int>
{
public:
int Foo() { return 2; }
};
class MyStringImpl : public MyInterface<std::string>
{
public:
std::string Foo() { return "haha"; }
};
template<class ImplType>
class MyHub
{
public:
static typename ImplType::Type Foo()
{
ImplType i;
return i.Foo();
}
private:
MyHub() { }
~MyHub() { }
};
int main()
{
std::cout << MyHub<MyIntImpl>::Foo() << "\n"; // prints 2
std::cout << MyHub<MyStringImpl>::Foo() << "\n"; // print haha
return 0;
}
Here is an example.
MyImpl is not a class template; so can't be passed as the template parameter of MyInterface.
You could change your MyInterface, MyImpl and MyHub classes to:
template<typename T>
class MyInterface{
public:
virtual T foo() = 0;
};
class MyImpl: public MyInterface<int>{
public:
using value_type = int;
value_type foo(){ return 1; /* dummy */ }
};
template<typename Impl, typename = std::enable_if_t<std::is_base_of<Impl, MyInterface<typename Impl::value_type>>::value>>
class MyHub{
public:
static auto foo(){
static Impl i;
return i.foo();
}
};
Which lets you use it the same way you are in your example.
The std::is_base_of check might be a little unnecessary in this case; but, this way you can't accidentally pass in another class that isn't derived from MyInterface with a method foo().
The STL uses value_type as a place holder for the underlying type of a template class. You could possibly do the same for your solution.
template<typename T>
struct MyInterface
{
typedef T value_type;
virtual T Foo() = 0;
}
class MyImpl : public MyInterface<int>
{
public:
int Foo() { /*...*/ }
};
template<typename ImplType>
class MyHub
{
public:
static typename ImplType::value_type Foo()
{
ImplType i;
return i.Foo();
}
private:
MyHub() { }
~MyHub() { }
};
Also note that in c++14, typename ImplType::value_type can be replaced by auto:
static auto Foo()
{
ImplType i;
return i.Foo();
}
The names of template parameters of template template parameters are effectively a purely documentational construct—they don't get included in the containing template's scope.
There's good reason for that: there is nothing to whcih they could refer in the containing template. When you have a template template parameter, you must pass a template as the argument to it, and not an instantiation of a template. In other words, you're passing a template without arguments as the argument.
This means your code is simply wrong—you're using MyImpl as an argument for MyHub, but MyImpl is a class. MyHub expects a template, not a class. The correct instantiation of MyHub would be MyHub<MyInterface>. Not that there are no template arguments after this use of MyInterface; we are passing in the template itself, not an instantiation of it.
Template template parameters are used rather rarely in practice. You only use them if you want to instantiate the parameter template with your own types. So I would expect your MyHub code to do something like this:
template <template <class> class ImplTemplate>
struct MyHub
{
typedef ImplTemplate<SomeMyHub_SpecificType> TheType;
// ... use TheType
};
This doesn't seem to be what you want to do. I believe you want a normal type template parameter, and provide a nested typedef for its T. Like this:
template <class T>
struct MyInterface
{
typedef T ParamType; // Added
virtual T Foo() = 0;
};
template<class ImplType>
class MyHub
{
typedef typename ImplType::ParamType T;
public:
static T Foo()
{
ImplType i;
return i.Foo();
}
private:
MyHub() { }
~MyHub() { }
};
int main()
{
int i = MyHub<MyImpl>::Foo();
return 0;
}
Now I have a template class
template <class T>
class b
{
void someFunc() {
T t;
t.setB();
}
};
I know the template T only will be instantiated into 2 classes.
class D
{
public:
void setB();
};
class R
{
public:
void SetB();
};
As we can see, class D's function name setB is not the same as R's function SetB. So in template class b I cannot only just use setB. So is there some method if I cannot revise D or R? Can I add some wrapper or trick into the template class to solve this problem?
Maybe a trait class can help you:
struct Lower {};
struct Upper {};
// trait for most cases
template <typename T>
struct the_trait {
typedef Lower Type;
};
// trait for special cases
template <>
struct the_trait<R> {
typedef Upper Type;
};
template <class T>
class b {
public:
void foo() {
foo_dispatch(typename the_trait<T>::Type());
}
private:
void foo_dispatch(Lower) {
T t;
t.setB();
}
void foo_dispatch(Upper) {
T t;
t.SetB();
}
};
As #Arunmu pointed, this technique is also known as Tag Dispatching.
You can specialise your template for the class that has different semantics:
template<>
class b<R>
{
void doWork() {
R obj;
obj.SetB();
// or R::SetB() if it was a static method.
}
};
Instead of using self programmed traits you can also check for the existence of a function with SFINAE.
If you want to switch your called method only one of them must exist in each class. My method provided will not work if the check find more then one of the tested methods!
The following example is written for C++14 but can also be used with c++03 if you replace the new library functions with self implemented ones ( which is of course not convenient )
The testing class has_Foo and has_Bar can also be embedded in a preprocessor macro, but I wrote it expanded to makes the things easier to read.
How it works and why there are some more intermediate steps are necessary are explained in the comments. See below!
#include <iostream>
// First we write two classes as example. Both classes represents
// external code which you could NOT modify, so you need an
// adapter to use it from your code.
class A
{
public:
void Foo() { std::cout << "A::Foo" << std::endl; }
};
class B
{
public:
void Bar() { std::cout << "B::Bar" << std::endl; }
};
// To benefit from SFINAE we need two helper classes which provide
// a simple test functionality. The solution is quite easy...
// we try to get the return value of the function we search for and
// create a pointer from it and set it to default value nullptr.
// if this works the overloaded method `test` returns the data type
// one. If the first test function will not fit, we cat with ... all
// other parameters which results in getting data type two.
// After that we can setup an enum which evaluates `value` to
// boolean true or false regarding to the comparison function.
template <typename T>
class has_Foo
{
using one = char;
using two = struct { char a; char b;};
template <typename C> static one test( typename std::remove_reference<decltype(std::declval<C>().Foo())>::type* );
template <typename C> static two test( ... ) ;
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
enum { Yes = sizeof(test<T>(0)) == sizeof(one) };
enum { No = !Yes };
};
template <typename T>
class has_Bar
{
using one = char;
using two = struct { char a; char b;};
template <typename C> static one test( typename std::remove_reference<decltype(std::declval<C>().Bar())>::type* );
template <typename C> static two test( ... ) ;
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
enum { Yes = sizeof(test<T>(0)) == sizeof(one) };
enum { No = !Yes };
};
// Now in your adapter class you can use the test functions
// to find out which function exists. If your class
// contains a Foo function the first one compiles and if the
// the class contains a Bar function the second one fits. SFINAE
// disable the rest.
// We need a call helper here because SFINAE only
// fails "soft" if the template parameter can deduced from the
// given parameters to the call itself. So the method
// Call forwards the type to test "T" to the helper method as
// as explicit parameter. Thats it!
template <typename T>
class X: public T
{
public:
template < typename N, std::enable_if_t< has_Foo<N>::value>* = nullptr>
void Call_Helper() { this->Foo(); }
template < typename N, std::enable_if_t< has_Bar<N>::value>* = nullptr>
void Call_Helper() { this->Bar(); }
void Call() { Call_Helper<T>(); }
};
int main()
{
X<A> xa;
X<B> xb;
xa.Call();
xb.Call();
}
How can someone make this code compile:
#include <iostream>
using namespace std;
enum E { A, B};
template< E x>
class C {
public:
#if( x == A)
static void foo() {
cout << "A";
}
#elif( x == B)
static void goo() {
cout << "B";
}
#endif
};
int main() {
C< A>::foo();
C< B>::goo();
return 0;
}
error: ‘goo’ is not a member of ‘C<(E)1u>’
I have two big classes which differs only a few lines, so I wanted to make enum template. The problem is that this lines have using keyword in them, so I don't know what to put there.
Is there some correct way to do it?
PS> I'm have to use C++03.
EDIT: A little clarification. I know about template<> construction, but I don't wanted to use it because this way I got a lot of code duplication. Maybe I can somehow make partial "template instanciation" (if this is correct term for template<>)?
Suppose I have two classes (and I will not have more):
class A {
public:
//…a lot of code…
//few lines that differs in A and B
}
class B {
//…the same mass of code…
//few lines that differs in A and B
}
So I decided to make template on enum:
enum E { A, B}
template< E>
class C{
//…common code…
}
Now I don't know what to do with this few lines that differs in A and B. I know that common way is to make template instanciation, but then I'll get exactly what I had with classes A and B.
From the OOP point I should use common Base for A and B. But the problem is that A and B is already the same. They differs only with line:
using CanStoreKeyValue< QString, Request>::set;
using CanStoreKeyValue< QString, Response>::set;
where Response and Request are typedefs. Moreover, in my code A and B are childs of the same templated abstract class. And of course they inherit it with different template param. This somehow brokes using of template enum — compiler just can't see that some virtual methods a no longer pure. So… that's why I'm asking what I'm asking. I thought that preprocessor could interact with template engine with #if-directives (on the end, they both are compile time processes).
You cannot use preprocessor to achieve what you are trying to do. What you need is a template specialization:
enum E { A, B};
template< E x>
class C;
template <>
class C<A> {
public:
static void foo() {
cout << "A";
}
};
template <>
class C<B> {
public:
static void goo() {
cout << "B";
}
};
Your updated problem still can be resolved by template specialization:
enum E { A, B };
template< E x >
struct CanStoreKeyValueHelper;
template<>
struct CanStoreKeyValueHelper<A> {
typedef CanStoreKeyValue< QString, Request>::set type;
};
template<>
struct CanStoreKeyValueHelper<B> {
typedef CanStoreKeyValue< QString, Response>::set type;
};
template< E x>
class SuperPuperBigClass {
public:
typedef typename CanStoreKeyValueHelper<x>::type set;
...
};
But it is not clear why you do not make it as simple as:
template<class T>
class SuperPuperBigClass {
public:
typedef typename CanStoreKeyValue<QString, T>::set set;
};
and instantiate it with Request and Response type
If you don't want specialization, I suppose constraining the functions with SFINAE is an option (Live at coliru):
template <E x>
class C {
public:
template <E y = x>
static typename std::enable_if<y == A>::type foo() {
cout << "A";
}
template <E y = x>
static typename std::enable_if<y == B>::type goo() {
cout << "B";
}
};
But if code duplication is your only issue, use specialization and put the common code in a base class (Live at Coliru), it's a bit cleaner:
class C_base {};
template <E x>
class C : public C_base {};
template <>
class C<A> : public C_base {
public:
static void foo() {
cout << "A";
}
};
template <>
class C<B> : public C_base {
public:
static void goo() {
cout << "B";
}
};
Currently, I have a CRTP base class which utilizes a traits class to determine the return type of it's member functions. I've been playing around with C++11 and have the following code which eliminates the need for the traits class, but requires default function template parameters. Is there some way to modify this to work in visual studio 2012 which doesn't support that feature of C++11?
#include <iostream>
using namespace std;
template<typename T, typename Ignore>
struct ignore { typedef T type; };
template<typename T>
struct A
{
template<class IgnoredParam = void>
auto foo() -> decltype(declval<typename ignore<T*, IgnoredParam>::type >()->foo_impl())
{
return static_cast<T*>(this)->foo_impl();
}
};
struct B : public A<B>
{
int foo_impl() { return 0;}
};
int main()
{
B b;
int i = b.foo();
cout << i << '\n';
}
You can simply use
decltype(declval<T>()->foo_impl())
as the deferred return type.