Ok the following code is copied from another stackoverflow question
here
template<typename T>
struct remove_pointer
{
typedef T type;
};
template<typename T>
struct remove_pointer<T*>
{
typedef typename remove_pointer<T>::type type;
};
While I do understand that this is a recursive definition in template, what puzzled me are the lines
template<typename T>
struct remove_pointer<T*>
does that mean remove_pointer will result in T=int*? Why wouldn't T=int**? explanation is appreciated.
This is a specialization for pointer types. Specializations may also have template parameters. So this template's type is just T in the general case but, if T is a pointer type, then its type is T with the pointer removed. Maybe it is more clear when giving the parameter a different name:
template<typename T>
struct remove_pointer
{
typedef T type;
};
template<typename S>
struct remove_pointer<S*> // specialization for T = S*
{
typedef typename remove_pointer<S>::type type;
};
i.e. in the general case type is just T, but if T is a pointer, then the template is instantiated for S, where T == S*.
PS: I think the special thing about this example is that the specialization introduces a new template parameter. A "normal" specialization would look like this:
template<>
struct remove_pointer<int*> // specialization for T = int*
{
typedef typename remove_pointer<int>::type type;
};
However, this isnt very useful, as we want it to work for any type. The solution is to introduce an additional template parameter on the specialization (S). Afaik this additional parameter has to be deducible from the parameters to the original template, in this case S can be deduced, because S is just T without the pointer.
Related
Before that I want to tell that I have tried to implement is_assignable on my own. There is no need to show me another examples - I have already seen some implementation.
I would like to fix my solution thanks to you (if it's possible, of course) that'll work out.
So, here is my code:
#include <iostream>
#include <type_traits>
#include <utility>
template<typename LambdaT>
struct is_valid_construction {
is_valid_construction(LambdaT) {}
typedef typename LambdaT lambda_prototype;
template<typename ValueTypeT, typename ExprTypeT = decltype(std::declval<lambda_prototype>()(std::declval<ValueTypeT>()))>
struct evaluate {
evaluate(ValueTypeT val) {
std::cout << "Right!";
}
typedef typename std::true_type value;
};
template<typename ValueTypeT> //The compiler ignores this definition
struct evaluate<ValueTypeT, decltype(std::declval<lambda_prototype>()(std::declval<int>()))> {
evaluate(ValueTypeT val) {
std::cout << "Nope";
}
typedef typename std::false_type value;
};
template<typename ValueTypeT>
void print_value(ValueTypeT val) {
evaluate evaluation(val);
}
};
struct ForTest {};
int main() {
is_valid_construction is_assignable([](auto x) -> decltype(x = x) { });
is_valid_construction is_less_comparable([](auto x) -> decltype(x < x) {});
is_valid_construction is_more_comparable([](auto x) -> decltype(x > x) {});
is_assignable.print_value(int{});
is_less_comparable.print_value(char{});
is_more_comparable.print_value(ForTest{});
return 0;
}
As you can see I am trying to define template structure within template structure. So, I excepted that if the invocation (with declval) of this lambda-expression with parameter of this type (rougly, in terms of substitution) is failed, then SFINAE goes further and should see that the second template definition could be convenient for instantiation. I am asking how could I fix my template structure and its default parameter to push SFINAE use the second definition?
SFINAE can be used in order to direct the compiler to choose a particular function overload, or a particular partial specialization of a class template. In the first case, substitution failures remove declarations from the overload set and in the second case, substitution failures remove the partial specialization declarations from consideration (causing either the primary template to be used, or a different partial specialization for which substitution succeeds).
But what you are trying to do here is backward: you have a situation where the primary template is potentially subject to substitution error, and you provide a partial specialization as an alternative. This can never work. Partial specialization matching begins after the template argument list to the primary template is fully known, therefore if a substitution error occurs in the primary template's template argument list, no specializations can be considered.
For example if we have
template <typename T, typename U = some_metafunction_of_T>
struct S;
template <typename T>
struct S<T, T>;
then the instantiation process of S<int> will first evaluate U for the primary template, and then, only once T and U are both known, the compiler can determine whether or not they are the same (which would allow the partial specialization to be used). If a substitution error occurs while computing U, the question of whether the partial specialization applies cannot even be asked.
To fix your code, you would have to switch the two definitions of evaluate. The primary template would have to be the "fallback", and the partial specialization would have to be potentially subject to substitution error.
as #Brian said, you should put the requirements at the primary template if the requirements are for all specializations, and put other requirements for each specialization at their own declarations:
template<typename T, typename = std::void_t</* global requirements */>>
struct S;
template<typename T>
struct S<T, std::void_t</* requirements for this specialization */>>;
and if you want one of specialization is prior to others, you can add its negative requirements to other specializations:
template<typename T, typename = std::void_t</* global requirements */>>
struct S;
template<typename T>
struct S<T, std::void_t<std::enable_if_t</* conditions for this specialization */>>>;
template<typename T>
struct S<T, std::void_t<std::enable_if_t<!/* conditions for the former specialization */>, /* requirements for this specialization */>>;
for your example, it should be like this:
template<typename Lambda>
struct is_valid_construction{
template<typename T, typename = void>
struct helper : std::false_type{};
template<typename T>
struct helper<T, std::void_t<decltype(std::declval<Lambda>()(std::declval<T>()))>> : std::true_type{};
template<typename V, typename = void>
struct evaluate;
template<typename V>
struct evaluate<V, std::enable_if_t<helper<V>::value>>;
template<typename V>
struct evaluate<V, std::void_t<std::enable_if_t<!helper<V>::value>, decltype(std::declval<Lambda>()(std::declval<int>()))>>;
};
by the way, you can use std::is_invocable to simplify this code:
template<typename Lambda>
struct is_valid_construction{
template<typename V, typename = void>
struct evaluate;
template<typename V>
struct evaluate<V, std::enable_if_t<std::is_invocable_v<Lambda, V>>>;
template<typename V>
struct evaluate<V, std::enable_if_t<!std::is_invocable_v<Lambda, V> && std::is_invocable_v<Lambda, int>>>;
};
Thanks to #RedFog and #Brian I could complete my code and I have got the such result:
#include <iostream>
#include <type_traits>
#include <utility>
template<typename LambdaT>
struct is_valid_construction {
is_valid_construction(LambdaT) {}
typedef LambdaT lambda_prototype;
template<class ValueT, class = void>
struct is_void_t_deducable : std::false_type {};
template<class ValueT>
struct is_void_t_deducable<ValueT,
std::void_t<decltype(std::declval<lambda_prototype>()(std::declval<ValueT>()))>> : std::true_type {};
template<class ValueT>
bool is_valid_for(ValueT value) {
if constexpr (is_void_t_deducable<ValueT>::value)
return true;
else
return false;
}
};
struct ForTest {};
int main() {
is_valid_construction is_assignable([](auto x) -> decltype(x * x) { });
std::cout << is_assignable.is_valid_for(0) << std::endl;
std::cout << is_assignable.is_valid_for(ForTest{});
return 0;
}
As they both said, that when I had declared template parameter like that:
template<typename ValueTypeT, typename ExprTypeT = decltype(std::declval<lambda_prototype>()(std::declval<ValueTypeT>()))>
the compiler didn't understand what a default value should the second template parameter assign and since both declarations are incompatible.
I am new one in template programming and I can try to explain the solution as simple as possible:
The second template parameter is (if to say not strictly!) should be void. So, the compiler can instantiate the template with second void parameter in two ways by means of first declaration or second declaration.
(It should be said that std::void_t<TemplateParam> becomes void if TemplateParam is well!)
If an instantiation with the second declaration is well, then the
second template parameter is void.
If an instantiation with the first declaration is well, then the
second template parameter is void.
So, we should help compiler to deduce both structures with the second template parameter void. When it tries to instantiate is_valid_for(ForTest{}) first of all it tries to deduce
std::void_t<decltype(std::declval<lambda_prototype>()(std::declval<ValueT>()))>
but gets substitution error. However, nothing prevents to deduce the second template parameter void in another way and the compilers takes the first declaration.
P.S. I know that this explanation is not good but it may help dummies like me!
Consider the following structs:
//Implementations provided elsewhere
struct A { A(int i, double d, std::string s); /* ... */ };
struct B { B(double d1, double d2); /* ... */ };
I have two conversion classes whose template signatures look like:
TupleAs< A, int, double, std::string > via1 { ... };
ArrayAs< B, double, 2 > via2 { ... };
Predictably, TupleAs converts a triplet of int,double, and std::string values into an object of type A. Similarly, ArrayAs converts a pair of two double values into an object of type B. (And yes, there are reasons why I cannot call the A and B constructors directly.)
Improving the syntax
I would like to change the syntax so I can do the following:
TupleAs< A(int,double,std::string) > via1 { ... };
ArrayAs< B(double,2) > via2 { ... };
which, I think, is more descriptive of a conversion process. The TupleAs template declaration and corresponding partial specialization would look like this:
template <typename T> struct TupleAs;
template <typename T, typename ... Args>
struct TupleAs<T(Args...)> { ... };
Compiler errors
However, if I try to do something similar with the ArrayAs version:
template <typename T> struct ArrayAs;
template <typename T, typename U, unsigned N>
struct ArrayAs<T(U,N)> { ... };
I get the following errors in clang (3.6) when trying to instantiate it (ArrayAs< B(double,2)> test;):
typeAs.cpp:14:22: error: unknown type name 'N'
struct ArrayAs<T(U,N)>{
^
typeAs.cpp:14:10: warning: class template partial specialization contains a template parameter that cannot be deduced; this partial specialization will never be used
struct ArrayAs<T(U,N)>{
^~~~~~~~~~~~~~~
typeAs.cpp:13:45: note: non-deducible template parameter 'N'
template<typename T, typename U, unsigned N>
^
The gcc error diagnostic is a little different, but I won't post it here.
I admit that my templating skills should be better than they are, and I also concede that an analogous std::function<B(double,2)> declaration clearly is nonsense. But can someone tell me why the particular syntax I'm trying to achieve is not allowed? I looked through the C++14 standard and had trouble finding the relevant portion, and I'm having trouble interpreting the clang diagnostic message.
When you specialize TupleAs:
template <typename T, typename ... Args>
struct TupleAs<T(Args...)>
You are basically overloading the notation for a function. You are specializing on a function that takes Args... and returns a T. That is a type. You may not be using that function as a function, or really ever think about it as being a type, but that is what it is.
On the other hand, here:
template <typename T, typename U, unsigned N>
struct ArrayAs<T(U,N)> { ... };
There is no such thing as a function that takes N. It could take unsigned, but it can't take a value. There is just no such reasonable thing. From your example, B(double, 2) simply does not make sense. At best, you could write something that would allow:
template <unsigned N> using size_ = std::integral_constant<size_t, N>;
ArrayAs< B(double,size_<2>) >
Or even:
ArrayAs< B(std::array<double, 2>) >
since now we're back to using types everywhere. Whether you prefer that or not is personal preference.
The key here is that types are first-class citizens when it comes to all things template metaprogramming, and values should be avoided where possible.
template <typename T> struct ArrayAs;
template <typename T, typename U, std::size_t N>
struct ArrayAs<T(std::array<U,N>)> { ... };
works, as would:
template<class T>
struct to_array;
template<class T, size_t N>
struct to_array< T[N] > { using type = std::array<T, N>; };
template<class T>
using arr = typename to_array<T>::type;
then:
ArrayAs< Bob( arr<int[3]> ) > some_var;
live example.
Sadly, directly using ArrayAs< Bob( int[3] ) > doesn't work due to how arrays in function types decay to pointers.
I need a template expression that selects the first argument type if the first argument is defined, else the second argument type.
select<int, float>::type // type evaluates to int
select<an_undefined_type, float>::type // type evaluates to float
... and the solution has to work with C++03 and Boost 1.33.1 :(
My goal is to accept both int and boost::optional<int> as a function template parameter T, so I can do something like:
template<typename T>
void fn(T& t)
{
int x = std::numeric_limits<select<T::value_type, T>::type>::digits;
}
since boost::optional<int>::value_type is defined.
C++11 solutions are also appreciated.
I don't see a way to do this with template specialization, since I'm trying to specialize not on types but on concepts. Basically, I would need one specialization that matches the any_integer concept and one specialization that matches the boost::optional<any_integer> concept.
I guess with C++11 I could accomplish this specific goal with:
std::conditional<std::is_integral<T>::value, T, T::value_type>::value
but I don't have C++11, and I want the more general solution.
I don't think you can achieve the exact notation you are looking for. However, I think you can use a slightly different notation to achieve what you are semantically after. The problem with your current notation
int x = std::numeric_limits<select<T::value_type, T>::type>::digits;
is that select<T0, T1> expects two types, i.e., the requirement for the types to be present isn't on the select<T0, T1> template but on the function calling it. The way I would change this is to use
int x = std::numeric_limits<select<typename get_value_type<T>::type, T>::type>::digits;
Now all what needs to happen is to have a get_value_type<T> which yields the nested type if present and some type select<T0, T1> is going to ignore if arrives there, e.g., void (or a custom marker type). The get_value_type<T> template should be fairly simple (I saw Dirk Holsopple's answer but I couldn't get it work):
template <typename T>
struct has_value_type
{
typedef char (&true_type)[1];
typedef char (&false_type)[2];
template <typename D> static true_type test(typename D::value_type*);
template <typename D> static false_type test(...);
enum { value = sizeof(test<T>(0)) == 1 };
};
template <typename T, bool = has_value_type<T>::value >
struct get_value_type
{
typedef T type; // EDIT
};
template <typename T>
struct get_value_type<T, true>
{
typedef typename T::value_type type;
};
Obviously, you might want to define your type-traits slightly different so you can use something like
int x = std::numeric_limits<typename get_type<T>::type>::digits;
This would return the nested type if there is a value_type and a type T otherwise.
I have a templated class Converter, and I'd like to do a partial specialization. The tricky part is I'd like to specialize it to MyFoo::Vec where MyFoo again can be specialized as a template parameter. If that sounds confusing, maybe the code itself makes it clearer:
#include <iostream>
#include <vector>
template<class To>
struct Converter {
Converter(int from, To& to) {
to = To(from);
}
};
template<class T>
struct Foo {
typedef std::vector<T> Vec;
Vec vec;
};
// Template specialization: Convert from 'From' to 'MyFoo::Vec':
template<class MyFoo>
struct Converter<typename MyFoo::Vec > { // Error: template parameters not
// used in partial specialization
Converter(int from, typename MyFoo::Vec& to) {
to.push_back(typename MyFoo::Vec::value_type(from));
}
};
int main() {
Foo<float> myfoo;
Converter<Foo<float> > converter(2, myfoo.vec);
}
This is just a mini example derived from my actual code. This question is not about how useful such a converter is; I'm just interested in getting the syntax right given that I need such a converter and its specialization.
It cannot be done directly. Consider that it is impossible to go from the nested type to the enclosing type for two reasons: first, the mapping might not be unique (multiple Foo might have the same nested Vec type) and even if it was the compiler would have to test all existing types (i.e. it cannot infer from the instantiation).
What you want to do can actually be done with SFINAE (untested code, you can read more here):
template <typename T, typename V = void>
struct Converter {}; // Default implementation
template <typename T>
struct Converter<T, T::Vec> {}; // specific if has nested Vec
Would any one knows according to what rules code below doesn't compile?
template <class T>
struct B
{
typedef T type;
};
template<class T>
struct X
{
};
template<class T>
struct X<B<T>::type*>//HERE I'M PARTIALLY SPECIALIZING (WELL, TRYING TO...)
{
};
Please see comment inside the code.
How do you think that will work? The compiler will look to see if there is a class T somewhere that has a typedef "type" to your class?
It just won't. Even though it's a pointer.
Remember that presumably your B template is presumably specialised in places so that type is not always T*, but it can't deduce it with reverse engineering.
For those who did not understand my answer fully, what you are asking the compiler to do is find a class U such that B::type is the class you pass in as a parameter.
class Foo;
class Bar;
template<> struct B<Foo>
{
typedef int type;
};
template<> struct B<Bar>
{
typedef int type;
};
X<int*> // ambiguous, T is Foo or Bar?
It is difficult to know exactly why you are trying to do what you are. You can do a partial specialization on all pointers and then a total specialization on specific pointers, which could be implement in terms of another template.
You need to use typename keyword as,
template<class T>
struct X<typename B<T>::type*>
{
};
It's because B<T>::type is a dependent name. So typename is required!
--
EDIT:
Even after putting typename, it isn't compiling. I think it's because deduction of type T in B<T> from X<U> is difficult, or possibly impossible, for the compiler. So I believe its non-deduced context.
See a similar example here and the discussion:
Template parameters in non-deduced contexts in partial specializations
However, if you change the specialization to this:
template<class T>
struct X<B<T> >
{
};
Then it becomes the deducible context, and so would compile.
Assuming you already added typename as suggested by Nawaz.
The problem is exactly explained in the error message you encounter: "template parameter is not deducible in partial specialization B<T>::type*. The problem is that B<T>::type and T is exactly the same for all types T. Consider the following example:
class MyClass1 {};
typedef typename B<MyClass>::type MyClass2; //(*)
X<MyClass*> obj1;
X<MyClass2*> obj2;
The result of line (*) is a type MyClass2 which is essentially MyClass1. So, obj1 and obj2 should be objects of the same class. Now, which version of template X should they use?
If you would expect the specialised version of X, tell me if the answer should be the same if line (*) is removed (and obviously obj2 as well). Still obj1 should be the specialised version of X as line (*) has nothing to do with it.
But now we expect the compiler to detect that some type can be potentially declared as B<T>::type although we never do this. We expect the compiler to verify all possible template instantiations to check if there is no strange typedef in one of them.
I hope this clarifies why such specialisation cannot be handled by the compiler.
An alternative that might help
I believe your problem could be attacked by creating a trait class for explicitly marking types that should be handled in a special way. Something like this:
template <bool v>
struct boolean_value {
static const bool value=v;
};
template <typename T>
struct is_my_interesting_type : public boolean_value<false> {};
class MyClass {
...
};
template <>
struct is_my_interesting_type<MyClass> : public boolean_value<true> {};
template <typename T, bool special>
class InternalX {
... //generic version of your template X
};
template <typename T>
class InternalX<T,true> {
... //special version of your template X
};
template <typename T>
class X : public InternalX<T,is_my_interesting_type<T>::value> {};
Also, you might be interesting how it is done in boost library, in particular Boost.Type_Traits
"The argument list cannot be identical to the non-specialized argument list (it must specialize something)"
see partial_specialization at en.cppreference.com