Why isn't typename interchangeable with decltype() for this usage? - c++14

For a given usage
template<typename T1>
class node{
public:
using sp2node = shared_ptr<node<T1>>;
using r_sp2node = shared_ptr<node<T1>>&;
public:
r_sp2Node getN();
private:
sp2node N;
};
(1)
template<typename T1> decltype(node<T1>::r_sp2node) node<T1>::getN(){
return N;
}
(2)
template<typename T1> typename node<T1>::r_sp2node node<T1>::getN(){
return N;
}
(1) generates the compiler error:
error: missing 'typename' prior to dependent type name
'node<T1>::r_sp2node'
whereas (2) compiles
Can someonene explain what is the difference between the above two?

There are two things wrong with the first example.
In decltype(node<T1>::r_sp2node), reading inside out, the compiler first needs to know what node<T1>::r_sp2node. Is it a type, or something else? This is why the typename disambiguator exists, and that is what the error message is all about.
The second problem is that decltype expects some expression, not a type. So even if you used typename, it still wouldn't compile. (As a simple example, decltype(int) won't even compile.)
To answer the question specifically, the difference between the two is that the first is not valid C++ and the second is the way to go.

Related

C++ Check if generic object has member function matching signature

first post, so hopefully not violating any etiquette. Feel free to give suggestions for making the question better.
I've seen a few posts similar to this one: Check if a class has a member function of a given signature, but none do quite what I want. Sure it "works with polymorphism" in the sense that it can properly check subclass types for the function that comes from a superclass, but what I'd like to do is check the object itself and not the class. Using some (slightly tweaked) code from that post:
// Somewhere in back-end
#include <type_traits>
template<typename, typename T>
struct HasFunction {
static_assert(integral_constant<T, false>::value,
"Second template parameter needs to be of function type."
);
};
template<typename C, typename Ret, typename... Args>
class HasFunction<C, Ret(Args...)> {
template<typename T>
static constexpr auto check(T*) -> typename is_same<
decltype(declval<T>().myfunc(declval<Args>()...)), Ret>::type;
template<typename>
static constexpr false_type check(...);
typedef decltype(check<C>(0)) type;
public:
static constexpr bool value = type::value;
};
struct W {};
struct X : W { int myfunc(double) { return 42; } };
struct Y : X {};
I'd like to have something like the following:
// somewhere else in back-end. Called by client code and doesn't know
// what it's been passed!
template <class T>
void DoSomething(T& obj) {
if (HasFunction<T, int(double)>::value)
cout << "Found it!" << endl;
// Do something with obj.myfunc
else cout << "Nothin to see here" << endl;
}
int main()
{
Y y;
W* w = &y; // same object
DoSomething(y); // Found it!
DoSomething(*w); // Nothin to see here?
}
The problem is that the same object being viewed polymorphically causes different results (because the deduced type is what is being checked and not the object). So for example, if I was iterating over a collection of W*'s and calling DoSomething I would want it to no-op on W's but it should do something for X's and Y's. Is this achievable? I'm still digging into templates so I'm still not quite sure what's possible but it seems like it isn't. Is there a different way of doing it altogether?
Also, slightly less related to that specific problem: Is there a way to make HasFunction more like an interface so I could arbitrarily check for different functions? i.e. not have ".myfunc" concrete within it? (seems like it's only possible with macros?) e.g.
template<typename T>
struct HasFoo<T> : HasFunction<T, int foo(void)> {};
int main() {
Bar b;
if(HasFoo<b>::value) b.foo();
}
Obviously that's invalid syntax but hopefully it gets the point across.
It's just not possible to perform deep inspection on a base class pointer in order to check for possible member functions on the pointed-to type (for derived types that are not known ahead of time). Even if we get reflection.
The C++ standard provides us no way to perform this kind of inspection, because the kind of run time type information that is guaranteed to be available is very limited, basically relegated to the type_info structure.
Your compiler/platform may provide additional run-time type information that you can hook into, although the exact types and machinery used to provide RTTI are generally undocumented and difficult to examine (This article by Quarkslab attempts to inspect MSVC's RTTI hierarchy)

Passing an unspecialised template to another template

Given the following code here in IDEOne:
#include <iostream>
#include <vector>
#include <list>
template<typename T>
class MyVectorCollection
{
using collection = std::vector<T>;
};
template<typename C, typename T>
class MyGenericCollection
{
using collection = C;
};
template<typename C, typename T>
class MyMoreGenericCollection
{
using collection = C<T>;
};
int main() {
// your code goes here
MyVectorCollection<int> a;
MyGenericCollection<std::list<int>, int> b;
MyMoreGenericCollection<std::list, int> c; // How to do this?
return 0;
}
I get the error:
prog.cpp:20:24: error: ‘C’ is not a template
using collection = C<T>;
^
prog.cpp: In function ‘int main()’:
prog.cpp:27:43: error: type/value mismatch at argument 1 in template parameter list for ‘template<class C, class T> class MyMoreGenericCollection’
MyMoreGenericCollection<std::list, int> c;
^
prog.cpp:27:43: note: expected a type, got ‘list’
How can I write my code such that I can use a C<T> at compile time without having an explicit list of potential specialisations, and avoiding macros, if possible? I realise std::list isn't a typename, but I don't know how to progress, and I have been unable to find a similar question here.
(Note that this is just an MCVE, my actual usage is much more involved.)
Just to tidy up, here is the solution. The search term I was looking for is template template, and whilst I did find a possible duplicate, I think this question and answer is much simpler to follow.
So, thanks to the hint from #Some programmer dude, I looked up template template and updated the code to this, which does compile:
template<template<typename, typename> class C, typename T>
class MyMoreGenericCollection
{
using collection = C<T, std::allocator<T>>;
};
We declare the first template parameter as a template itself, and remembering that the standard library constructors take two parameters, we need to make the inner template take two parameters. There is (as far as I am aware) no way to automatically use the default second parameter, so for the sake of this example I explicitly state the default.
I could of course add a third parameter to the master template that could be used to specify the allocator, which itself would also be a template, but I leave that as an exercise for th reader.

static_assert with partial template specialization

template<typename T, typename U = void>
struct S { /* static_assert(0, "type unsupported"); */ };
template<typename T>
struct S<T, typename std::enable_if<std::is_integral<T>::value, void>::type> {
void foo() {}
};
...
S<int> i;
i.foo();
S<double> d;
// d.foo();
I would be expecting that the "master template" would never be instantiated for the case of int, but if I uncomment the static_assert, the S<int> instantiation will fail. Even a lone typedef S<int> Si; would fail to compile. (GCC 4.9.2 Cygwin)
What I aimed to achieve is not for S<double> to fail at the foo() call, but at the instantiation of the template itself, and that with a meaningful error message. I'm aware I can do something like typename T::nonexistent_type t; in the master template which will prevent the template for compiling, but that'd be inferior to a static_assert message. (Note: putting the static_assert within a function definition in the master template still fails compilation for S<int>)
Why does the static_assert fail even though that template is not instantiated? Is this mandated (or perhaps "unspecified") by the standard? Is there a way to fail with a static_assert the way I wish to?
The expression in the static_assert must be dependent on a template parameter if you wish it to be instantiation-time only. This is guaranteed by Standard- the implementation may (but has no obligation to) check static_assertions in templates that are not dependent on any template parameter.
Your code is a strange roundabout way of doing something like
template<typename T> struct S {
static_assert(std::is_integral<T>::value, "type unsupported");
void foo() {}
};
This clearly communicates to the compiler the dependency between the expression and the template parameter, and is far clearer and easier to read as well. I actually couldn't quite figure out if you wanted compilation to fail for integral types or for non-integral types.

boost::variant and operator<< overloading

I wanted to test a simple thing like the following:
#include <iostream>
#include <boost/variant.hpp>
template<typename T1,typename T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1,T2>& dt){
os << dt.first << dt.second;
return os;
}
int main(){
boost::variant<int, std::pair<int,int>, bool> v;
v = std::pair<int,int>(3,3);
std::cout << v << std::endl;
}
This should actually work, because for normal types, like int, double and so on, it compiles.
boost::variant has a printer vistor which it uses internally to output the content to the stream.
Actually this fails to compile, but I do not really know the problem:
The codes fails here: in variant_io.hpp
template <typename OStream>
class printer
: public boost::static_visitor<>
{
private: // representation
OStream& out_;
public: // structors
explicit printer(OStream& out)
: out_( out )
{
}
public: // visitor interface
template <typename T>
void operator()(const T& operand) const
{
out_ << operand; // HEEEEEEERRRRREE!!!!!!!!!!!!
}
private:
printer& operator=(const printer&);
};
With the message:
/usr/local/include/boost/variant/detail/variant_io.hpp|64|error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
Does someone know what I did wrong, and why?
Thanks a lot!
Most likely it's not finding your overload of operator <<, and then gets confused trying to match some other overload, leading to whatever message you're getting.
What you did wrong: You overloaded the stream operator in the global namespace instead of the namespace the right-hand-side class is defined in, so it's not found by ADL.
Trying to overload the stream operator for a standard class is a doomed exercise in the first place, unfortunately. You can't actually do that. I'm not sure if there is an explicit rule against it. However, if you place the operator in namespace std as you have to in order to make it properly findable by ADL, you violate the rule that you can't add your own stuff to namespace std except in very specific cases, this not being one of them.
The bottom line is that std::pair doesn't have a stream operator, and it's not possible to legally add a generic one that is useful. You can add one for a specific instantiation, if one of the parameters is a class you defined yourself; in this case the operator needs to be placed next to your own class.
Overloaded operator<< must be findable by argument dependent lookup. That means you have to put it in associated namespace of one of the arguments.
The first argument has only one associated namespace, std. The second also has only one associated namespace, std. However it is only permitted to overload symbols in std for user-defined types. Since std::pair<int, int> is not user-defined type, this is not allowed. However it is allowed for a structure or class you define yourself. Obviously in that case it is easier to place the overload to your namespace, not std.
That said if you put that overload in namespace std, it will actually work.
Also note, that boost::tuple does have operator<< (in separate header that you have to include, but it does), so you can use that instead.

C++0x Function delete - Delete all but certain types

In C++0x, I can do something like this:
double f(double x) { return x; }
template<class T>
T f(T x) = delete;
To prevent f() from being called on any other type than double.
What I'm trying to do is similar, however, not quite the same.
I have a function that operates on pointer arrays. For example:
template<class T>
T* some_string_function(T* x);
I want to be able to make T work for char, char16_t, and char32_t, but not any other type. I was thinking that C++0x's delete would be a good way to accomplish this. Basically, I want to be able to prevent this function from working with any type that isn't one of the three Unicode char types, but I still want to have the benefits of function templates, which allow me to generalise types and avoid repeating code.
What would be the best way to solve this problem? Is it possible?
Use boost::enable_if, along with type traits.
template<class T>
T* some_string_function(T* x, boost::enable_if<is_char_type<T>);
(assuming is_char_type is a type trait you define, which evaluates to true for the desired types, and false for all others)
You could do it using type_traits:
template<typename T>
typename enable_if<is_same<char, T>::value || is_same<char16_t, T>::value || is_same<char32_t, T>::value, T*>::type some_string_function(T *x)
{
return x;
}
Though you'd have to specifically specify const as well if you want to allow that.
I think the best way to do it is using a combination of static_assert and is_same (Both C++0x features). This also allows for a more friendly error message when you make an invalid call to the function.
#include <iostream>
using namespace std;
template<typename T> T* f(T*)
{
static_assert
(is_same<T, char>::value
|| is_same<T, char16_t>::value
|| is_same<T, char32_t>::value,
"Invalid Type, only char pointers allowed");
}
int main()
{
cout<<*f(new char('c'));//Compiles
cout<<*f(new int(3));//Error
}

Resources