Is it possible to specialize a template class to take additional template parameters ?
For example:
template <typename T>
struct X {
void foo() { cerr << "Generic" << endl;}
};
template <>
template <bool b>
struct X<int> {
void foo() { cerr << "Specialization" << endl;}
};
I could not make the above work with g++, but maybe there is some trick which will make this work.
Edit: I don't want to move the template <bool b> to the base template X, because it is feature of only X<int>.
If I have to, is there a way I can allow users to not have to specify any values for it? I would really like
an approach that does not go down this route.
You could change your primary template to accept a proxy traits class instead:
template <typename T>
struct Foo
{
typedef typename T::type type;
// work with "type"
void static print() { std::cout << T::message << std::endl; }
}
Then define the trait class:
template <typename T>
struct traits
{
typedef T type;
static const char * const message = "Generic";
};
Now you can instantiate Foo<traits<double>> and Foo<traits<int>>, and you can encapsulate additional behaviour into the traits class, which you can specialize as needed.
template <>
struct traits<int>
{
typedef int type;
static const char * const message = "Specialized";
};
Related
#include <iostream>
using namespace std;
template <typename T = int>
struct Foo {
T t;
Foo() { cout << "Foo" << endl; }
};
template <typename T>
struct Baz {
T t;
Baz() { cout << "Baz" << endl; }
};
template <typename T>
struct Bar {
T t;
Bar() { cout << "Bar" << endl; }
};
template <template <typename X> class T>
struct Bar {
T data;
Bar() : data() { cout << "Bar" << endl; }
};
int main()
{
Bar<Foo<>> a;
Bar<Baz<float>> b;
Bar<int> c;
return 0;
}
I'm just beginning to learn about templates. And I am really confused with template template parameters. I understand that you are passing a template as an argument. In my template class for Bar where it receives a template template argument, what does <typename X> represent? Is typename X a template parameter for class T?
template <template <typename X> class T>
struct Bar {
T data;
Bar() : data() { cout << "Bar" << endl; }
};
Also, when I call my template template argument in the main function, I get errors that there are no default constructors for Bar. Why is that?
template template parameters allow you pass templates to other templates.
They are not concrete types and need to be parameterised order to instaciate them.
In my template class for Bar where it receives a template template
argument, what does <typename X> represent?
From the standard [basic.scope.temp];
The declarative region of the name of a template parameter of a
template template-parameter is the smallest template-parameter-list in
which the name was introduced.
This basically says the name is only available within the that template template's parameters list.
For many cases it is sufficient to just put typename without a name for a template template parameter, but names may serve to document your code.
However an example of when it is useful to give it a name is if another non type template parameter depends on it.
For example, template <template <typename X, X> typename Y>.
With respect too your sample code, you have two problems with the second declaration of Bar. First is that Bar has already been declared to accept a type, not a template.
Your second declaration conflicts as it is declared to accept a template.
What you require here is a specialization of Bar, where the specialization resolves to a single Type, matching the primary template.
For instance,
template <template <typename> class T,typename Y>
struct Bar<T<Y>> {
T<Y> data;
Bar() : data() { cout << "Bar" << endl; }
};
The important thing to notice here is that the template parameters in the specialization can be whatever you need. It is the part after struct Bar that must match the primary template. All of the parameters in the specialization will be deduced from the type passed as the template parameter to your instantiation of Bar.
Your second problem is that you declare a member of Bar to be of type T. T is a template in the second case, and you cannot instantiate a template
without parameterising it.
Here is a working example of your code with the specialization of Bar.
#include <iostream>
using namespace std;
template <typename T = int>
struct Foo {
T t;
Foo() { cout << "Foo" << endl; }
};
template <typename T>
struct Baz {
T t;
Baz() { cout << "Baz" << endl; }
};
template <typename T>
struct Bar {
T t;
Bar() { cout << "Bar" << endl; }
};
template <template <typename > class T,class Y>
struct Bar<T<Y>>
{
T<Y> data;
Bar() : data() { cout << "Bar Specialization" << endl; }
};
int main()
{
Bar<Foo<>> a; //matches the specialization with T = template<typename> Foo and Y=int
Bar<Baz<float>> b; //matches the specialization with T = template<typename> Baz and Y=float
Bar<int> c; //matches the primary template with T=int
return 0;
}
Demo
typename X is only part of the template template parameters signature, you can just aswell write template<template<typename> class T> (without a name for the parameter of T).
Since T is itself a template, you need to instantiate it before you can use it as a class. The signature tells you what the template needs to be instantiated, in this case, it needs one type name.
template<typename X>
struct GenericThing
{
X data;
};
template<template<typename> class T, typename E>
struct Bar
{
T<E> sub; // instantiate T with E
Bar() : sub() { cout << "Bar" << endl; }
};
int main()
{
Bar<GenericThing, int> intbar;
Bar<GenericThing, float> floatbar;
return 0;
}
template <typename T>
void func_template(T& con) {
for (const auto& c : con)
std::cout << c << std::endl;
}
/*
Nested Templates
template <
template <
// # of type args that will be included in the nested template
typename,
...
>
// # of different types yo
typename T1,
...
typename TN
>
*/
template <template<typename, typename> typename V, typename T>
void func_template3(V<T, std::allocator<T>>& vec) {
for (const auto& elem : vec)
std::cout << elem << std::endl;
}
template <template<typename, typename, typename, typename> typename M, typename T1, typename T2>
void func_template4(M<T1, T2, std::less<T1>, std::allocator<std::pair<const T1, T2>>> & dict) {
for (const auto& pair : dict)
std::cout << pair.first << " " << pair.second << std::endl;
}
I just learned C++ a month ago, so please bear with me. The above is the way I personally look at it. the func_template3 and func_template4 provides an example of a template printing vector and map containing any type. I find that paying attention to VS "No instance of function template 'XXXX' matches the argument list error" very useful in trying to determine the composition of built-in types for the data structure that you should include in the template.
For example:
Prior to implementing to func_template4, I used an std::map variable as an argument for func_template3, which then VS prompted me with the following error
So when I was implementing funct_template4, I basically used the "arguments types are:(..." part of the error to guide me on what other built-in types should be included.
I've heard arguments that implementing nested templates are typically unnecessary, since it could have been achieved via func_template1; however, I somewhat disagree because the code that you would write in func_template1 actually depend largely on what data structure you intend to use the template with. Just my 2 cents from a C++ noob.
Can be template function within class template specialized outside of the class template?
What is the syntax for it?
Following code gives unable to match function definition to an existing declaration in MSVC2010
#include <iostream>
template <typename T>
struct Test
{
template <typename S>
void test(const S & t);
//this works
//template<> void test(const double & t) { std::cout << t << "D \n"; }
T member;
};
//this doesn't work
template <typename T>
template <>
void Test<T>::test(const double & t)
{
std::cout << t << "D \n";
}
int main()
{
Test<int> t;
t.test(7.0);
}
edit
I can use overload as suggested in answers, because I use it little differently, here is how:
#include <iostream>
template <typename T>
struct Test
{
template <typename S>
void test() { std::cout << "Any type \n"; }
template <>
void test<double>() { std::cout << "Double! \n"; }
T member;
};
int main()
{
Test<int> t1;
Test<int> t2;
t1.test<float>();
t2.test<double>();
}
and I want specialization for double outside of the struct.
Why I use it like this you ask? In real scenario I have built factory class which is used like:
Factory<SomePolicy> f;
f.create<MyType>(arg1, arg2, ...)
and I need specialization of create for specific type which won't pollute header file.
As far as I know you can't. But you can just overload your test function like this:
template <typename T>
struct Test
{
template <typename S>
void test(const S & t);
void test(const double &); // <-- Add this
T member;
};
template <typename T>
// template<> // <-- Remove this
void Test<T>::test(const double & t)
{
std::cout << t << "D \n";
}
Which should be totally equivalent to what you want to do.
I do not believe you can specialize the inner template without specializing the outer. You could, however, use partial specialization:
Edit: It appears that only classes can be partially specialized. Again, I haven't tested it. You can find more here
template <typename T, typename S>
struct Test
{
void test(const S &s);
};
template <typename T>
struct Test<T, float>
{
void test (const float &s)
{
<<do something>>
}
}
I have seen this question which allows one to check for the existence of a member function, but I'm trying to find out whether a class has a member type.
In the example below, both evaluate to "false", but I would like to find a way so that has_bar<foo1>::value evaluates to false, and has_bar<foo2>::value evaluates to true.
Is this possible?
#include <iostream>
struct foo1;
struct foo2 { typedef int bar; };
template <typename T>
class has_bar
{
typedef char yes;
typedef long no;
template <typename C> static yes check( decltype(&C::bar) ) ;
template <typename C> static no check(...);
public:
enum { value = sizeof(check<T>(0)) == sizeof(yes) };
};
int main()
{
std::cout << has_bar<foo1>::value << std::endl;
std::cout << has_bar<foo2>::value << std::endl;
return 0;
}
Edit: implementing a specialisation in response to the answers below:
...if you use C::bar in the target template, the template will be
discarded automatically for types that don't have that nested type.
I have tried to do this, but am clearly missing something
#include <iostream>
struct foo1;
struct foo2 { typedef int bar; };
template <typename T, typename U = void>
struct target
{
target()
{
std::cout << "default target" << std::endl;
}
};
template<typename T>
struct target<T, typename T::bar>
{
target()
{
std::cout << "specialized target" << std::endl;
}
};
int main()
{
target<foo1>();
target<foo2>();
return 0;
}
Try this
template<class T>
struct Void {
typedef void type;
};
template<class T, class U = void>
struct has_bar {
enum { value = 0 };
};
template<class T>
struct has_bar<T, typename Void<typename T::bar>::type > {
enum { value = 1 };
};
You cannot obtain a pointer to member to a type member:
template <typename C> static yes check( decltype(&C::bar) ) ;
The subexpression &C::bar will only be valid when bar is a non-type member of C. But what you need to check is whether it is a type. A minimal change to your template could be:
template <typename C> static yes check( typename C::bar* ) ;
If bar is a nested type of C, then that function overload will be a valid candidate (the 0 will be a pointer to whatever C::bar type is), but if C does not contain a nested bar then it will be discarded and the second test will be the only candidate.
There is a different question as of whether the trait is needed at all, since if you use C::bar in the target template, the template will be discarded automatically for types that don't have that nested type.
EDIT
What I meant is that in your approach you need to create a trait for each and every possible nested type, just to generate a template that does or does not hold a nested type (enable_if). Let's take a different approach... First we define a general utility to select a type based on a condition, this is not required for this problem, and a simpler template <typename T> void_type { typedef void type; }; would suffice, but the utility template can be useful in other cases:
// General utility: if_<Condition, Then, Else>::type
// Selects 'Then' or 'Else' type based on the value of
// the 'Condition'
template <bool Condition, typename Then, typename Else = void>
struct if_ {
typedef Then type;
};
template <typename Then, typename Else>
struct if_<false, Then, Else > {
typedef Else type;
};
Now se just need to use SFINAE for class template specializations:
template <typename T, typename _ = void>
struct target {
// generic implementation
};
template <typename T>
struct target<T, typename if_<false,typename T::bar>::type> {
// specialization for types holding a nested type `T::bar`
};
Note that the main difference with your approach is the use of an extra intermediate template (the one for which Substitution will Fail --and Is Not An Error) that yields a void type (on success). This is the reason why the void_type template above would also work: you just need to use the nested type as argument to a template, and have that fail, you don't really care what the template does, as long as the evaluation is a nested type (that must be void) if it succeeds.
In case it is not obvious (it wasn't at first for me) why your approach doesn't work, consider what the compiler needs to do when it encounters target<foo2>: The first step is finding that there is a template called target, but that template takes two arguments of which only one was provided. It then looks in the base template (the one that is not specialized) and finds that the second argument can be defaulted to void. From this point on, it will consider your instantiation to be: target<foo2,void> (after injecting the defaulted argument). And it will try to match the best specialization. Only specializations for which the second argument is void will be considered. Your template above will only be able to use the specialized version if T::bar is void (you can test that by changing foo2 to: struct foo2 { typedef void bar; }. Because you don't want the specialization to kick in only when the nested type is void you need the extra template that will take C::bar (and thus fail if the type does not contain a nested bar) but will always yield void as the nested type.
C++20 Update:
It is now much more easier to check whether a given type contains a specific type definition.
template<typename T>
concept has_bar = requires {
typename T::bar;
};
... so your example code evolves to this:
#include <iostream>
struct foo1;
struct foo2 { typedef int bar; };
template <typename T, typename U = void>
struct target
{
target()
{
std::cout << "default target" << std::endl;
}
};
template<typename T>
requires(has_bar<T>)
struct target<T>
{
target()
{
std::cout << "specialized target" << std::endl;
}
};
int main()
{
target<foo1>();
target<foo2>();
return 0;
}
Example on gcc.godbolt: https://gcc.godbolt.org/z/a15G13
I prefer to wrap it in macro.
test.h:
#include <type_traits>
template<typename ...>
struct void_type
{
using type = void;
};
template<typename ...T>
using void_t = typename void_type<T...>::type;
#define HAS_TYPE(NAME) \
template<typename, typename = void> \
struct has_type_##NAME: std::false_type \
{}; \
template<typename T> \
struct has_type_##NAME<T, void_t<typename T::NAME>>: std::true_type \
{} \
HAS_TYPE(bar);
test.cpp:
#include <iostream>
struct foo1;
struct foo2 { typedef int bar; };
int main()
{
std::cout << has_type_bar<foo1>::value << std::endl;
std::cout << has_type_bar<foo2>::value << std::endl;
return 0;
}
Possibly easy to solve, but its hard to find a solution to this:
Is it possible to (partially) specialize for a whole set of types?
In the example "Foo" should be partially specialized for (T,int) and (T,double) with only one template definition.
What I can do is define a specialisation for (T,int). See below. But, it should be for (T,int) and (T,double) with only one function definition (no code doubling).
template <typename T,typename T2>
struct Foo
{
static inline void apply(T a, T2 b)
{
cout << "we are in the generic template definition" << endl;
}
};
// partial (T,*)
template <typename T>
struct Foo<T, int > // here something needed like T2=(int, double)
{
static inline void apply(T a, T2 b)
{
cout << "we are in the partial specialisation for (T,int)" << endl;
}
};
Any ideas how to partially specialize this for (T,int) and (T,double) with one template definition?
If I understood your question correctly, then you can write a base class template and derive from it, as illustrated below:
template <typename T, typename U>
struct Foo_Base
{
static inline void apply(T a)
{
cout << "we are in the partial specialisation Foo_Base(T)" << endl;
}
};
template <typename T>
struct Foo<T, int> : Foo_Base<T, int> {};
template <typename T>
struct Foo<T, double> : Foo_Base<T, double> {};
Although its not one template definition (as you asked for), but you can avoid the code duplication.
Demo : http://www.ideone.com/s4anA
I believe you could do this using Boost's enable_if to enable the partial specialisation for just the types you want. Section 3.1 shows how, and gives this example:
template <class T, class Enable = void>
class A { ... };
template <class T>
class A<T, typename enable_if<is_integral<T> >::type> { ... };
In code:
template<class T>
struct is_builtin
{
enum {value = 0};
};
template<>
struct is_builtin<char>
{
enum {value = 1};
};
template<>
struct is_builtin<int>
{
enum {value = 1};
};
template<>
struct is_builtin<double>
{
enum {value = 1};
};
template<class T>
struct My
{
typename enable_if<is_builtin<T>::value,void>::type f(T arg)
{
std::cout << "Built-in as a param.\n";
}
typename enable_if<!is_builtin<T>::value,void>::type f(T arg)
{
std::cout << "Non - built-in as a param.\n";
}
};
struct A
{
};
int main()
{
A a;
My<int> m;
My<A> ma;
m.f(1);
ma.f(a);
return 0;
}
I'm getting an error:
error C2039: 'type' : is not a member of 'std::tr1::enable_if<_Test,_Type>'
Obviously I don't understand how to use enable_if. What I was thinking was that I can enable one or the second one member function from a set of member functions during compilation time but it does not work. Could anyone please explain to me how to do it correctly?
Edited
What I really can't understand is why isn't there typedef in one of those def. Compiler cannot find it and it wont compile it.
You can't use class template parameters to get SFINAE for member functions.
You either need to
make the member function a member function template instead and use enable_if on the member function template's template parameters or
move the member function f into a policy class and specialize the class template using enable_if.
Here's how it works (note that for convenience I replaced your is_builtin trait with std::is_arithmetic and used further C++11 stuff, but it works any way):
template<class T>
struct My
{
template<typename T_ = T, std::enable_if_t<std::is_arithmetic<T_>::value>* = nullptr>
void f(T_ arg)
{
std::cout << "Built-in as a param.\n";
}
template<typename T_ = T, std::enable_if_t<!std::is_arithmetic<T_>::value>* = nullptr>
void f(T_ arg)
{
std::cout << "Non - built-in as a param.\n";
}
};
DEMO
The crucial part is to bring the template parameter into the immediate context by using a default function template parameter T_ which equals the class template parameter T. For more details, see this question.
You can fix your code by using modified enable_if
template < typename T >
struct __Conflict {};
template <bool B, class T = void>
struct __enable_if { typedef __Conflict<T> type; };
template <class T>
struct __enable_if<true, T> { typedef T type; };
Example of usage:
template <typename T>
class Lazy
{
public:
void _ctor(bool b);
void _ctor(typename __enable_if<!std::is_same<T, bool>::value, T>::type);
};
template <typename T>
void Lazy<T>::_ctor(bool b)
{
std::cout << "bool " << b << std::endl;
};
template <typename T>
void Lazy<T>::_ctor(typename __enable_if<!std::is_same<T, bool>::value, T>::type t)
{
std::cout << "T " << t << std::endl;
};
int main(int argc, char **argv)
{
Lazy<int> i;
i._ctor(10);
i._ctor(true);
Lazy<bool> b;
b._ctor(true);
return 0;
}
enable_if expects a metafunction. To use a bool you need enable_if_c. I'm surprised you're not getting errors explaining THAT problem.
You can fix your metafunction by declaring a 'type' typedef inside that is simply itself. Then you can use boost::enable_if<is_builtin<T>>::type