Const and non const template specialization - c++

I have a class template which I use to get the size of a variable:
template <class T>
class Size
{
unsigned int operator() (T) {return sizeof(T);}
};
This works fine but for strings I want to use strlen instead of sizeof:
template <>
class Size<char *>
{
unsigned int operator() (char *str) {return strlen(str);}
};
The problem is when I create an instance of size with const char * it goes to the unspecialized version. I was wondering if there is a way to capture both the const and non-const versions of char * in on template specialization? Thanks.

Use this technique:
#include <type_traits>
template< typename T, typename = void >
class Size
{
unsigned int operator() (T) {return sizeof(T);}
};
template< typename T >
class Size< T, typename std::enable_if<
std::is_same< T, char* >::value ||
std::is_same< T, const char* >::value
>::type >
{
unsigned int operator() ( T str ) { /* your code here */ }
};
EDIT: Example of how to define the methods outside of the class definition.
EDIT2: Added helper to avoid repeating the possibly long and complex condition.
EDIT3: Simplified helper.
#include <type_traits>
#include <iostream>
template< typename T >
struct my_condition
: std::enable_if< std::is_same< T, char* >::value ||
std::is_same< T, const char* >::value >
{};
template< typename T, typename = void >
struct Size
{
unsigned int operator() (T);
};
template< typename T >
struct Size< T, typename my_condition< T >::type >
{
unsigned int operator() (T);
};
template< typename T, typename Dummy >
unsigned int Size< T, Dummy >::operator() (T)
{
return 1;
}
template< typename T >
unsigned int Size< T, typename my_condition< T >::type >::operator() (T)
{
return 2;
}
int main()
{
std::cout << Size< int >()(0) << std::endl;
std::cout << Size< char* >()(0) << std::endl;
std::cout << Size< const char* >()(0) << std::endl;
}
which prints
1
2
2

And you should also be able to write, of course:
template <>
class Size<const char *>
{
unsigned int operator() (const char *str) {return strlen(str);}
};
template <>
class Size<char *> : public Size<const char *>
{ };
...and, should you need to:
template <size_t size>
class Size<char[size]> : public Size<const char *>
{ };
template <size_t size>
class Size<const char[size]> : public Size<const char *>
{ };

One way is to use a helper function in order to determine if the template type is a char * or a char const *. You can do this with a simple struct. Then you can use SFINAE to select the proper specialization of your Size struct.
#include <cstring>
#include <iostream>
#include <boost/utility/enable_if.hpp>
template<typename T>
struct is_cstring {
enum { value = false };
};
template<>
struct is_cstring<char *> {
enum { value = true };
};
template<>
struct is_cstring<char const *> {
enum { value = true };
};
template<typename T, typename = void>
struct Size;
template<typename T>
struct Size<T, typename boost::disable_if<is_cstring<T> >::type> {
unsigned int operator ()(T const &) const {
return sizeof(T);
}
};
template<typename T>
struct Size<T, typename boost::enable_if<is_cstring<T> >::type> {
unsigned int operator ()(T const &str) const {
return strlen(str);
}
};
int main() {
std::string blah = "afafasa";
char *x = "asdfsadsad";
std::cout << Size<int>()(4) << std::endl;
std::cout << Size<char const *>()("blahblah") << std::endl;
std::cout << Size<char *>()(x) << std::endl;
}
The printed result is:
4
8
10

Related

Want kind of constexpr switch case on type

I am currently doing this trick to have a cstring based on a type:
template<class ListT> static char constexpr * GetNameOfList(void)
{
return
std::conditional<
std::is_same<ListT, LicencesList>::value, "licences",
std::conditional<
std::is_same<ListT, BundlesList>::value, "bundles",
std::conditional<
std::is_same<ListT, ProductsList>::value, "products",
std::conditional<
std::is_same<ListT, UsersList>::value, "users",
nullptr
>
>
>
>;
}
But this code is not very good-looking, and if we want to check more types, this could be unreadable. Is it a way to do the same thing as if there were a switch case block?
Actually, the code is more complicated than that, because std::conditional need some type, so we need some class to do the trick:
struct LicenceName { static char constexpr * value = "licences"; };
for example.
I think it would be easier using template specialization
Example code:
#include <iostream>
struct A{};
struct B{};
struct C{};
struct D{};
template<typename T> constexpr const char* GetNameOfList();
//here you may want to make it return nullptr by default
template<>constexpr const char* GetNameOfList<A>(){return "A";}
template<>constexpr const char* GetNameOfList<B>(){return "B";}
template<>constexpr const char* GetNameOfList<C>(){return "C";}
int main(){
std::cout << GetNameOfList<A>() << '\n';
std::cout << GetNameOfList<B>() << '\n';
std::cout << GetNameOfList<C>() << '\n';
//std::cout << GetNameOfList<D>() << '\n'; //compile error here
}
You don't need to resort to metaprogramming, plain ifs work just fine:
template<class ListT>
constexpr char const *GetNameOfList() {
if(std::is_same<ListT, A>::value) return "A";
if(std::is_same<ListT, B>::value) return "B";
if(std::is_same<ListT, C>::value) return "C";
if(std::is_same<ListT, D>::value) return "D";
return nullptr;
}
See it live on Coliru
You could create constexpr array of strings plus tuple of list types to create mapping list type -> index -> name (if you need the mapping index -> types containing strings just use tuple instead of array). c++17 approach could look as follows:
#include <type_traits>
#include <tuple>
#include <utility>
#include <iostream>
struct LicencesList{};
struct BundlesList{};
struct ProductsList{};
struct UsersList{};
using ListTypes = std::tuple<LicencesList, BundlesList, ProductsList, UsersList>;
constexpr const char *NameList[] = {"licences", "bundles", "products", "users"};
template <class Tup, class, class = std::make_index_sequence<std::tuple_size<Tup>::value>>
struct index_of;
template <class Tup, class T, std::size_t... Is>
struct index_of<Tup, T, std::index_sequence<Is...>> {
static constexpr std::size_t value = ((std::is_same<std::tuple_element_t<Is, Tup>, T>::value * Is) + ...);
};
template<class ListT> static const char constexpr * GetNameOfList(void) {
return NameList[index_of<ListTypes, ListT>::value];
}
int main() {
constexpr const char *value = GetNameOfList<BundlesList>();
std::cout << value << std::endl;
}
[live demo]
If you want to maintain c++11 compatibility the approach would be just a little bit longer (I used here Casey's answer to implement index_of structure):
#include <type_traits>
#include <tuple>
#include <iostream>
struct LicencesList{};
struct BundlesList{};
struct ProductsList{};
struct UsersList{};
using ListTypes = std::tuple<LicencesList, BundlesList, ProductsList, UsersList>;
constexpr const char *NameList[] = {"licences", "bundles", "products", "users"};
template <class Tuple, class T>
struct index_of;
template <class T, class... Types>
struct index_of<std::tuple<T, Types...>, T> {
static const std::size_t value = 0;
};
template <class T, class U, class... Types>
struct index_of<std::tuple<U, Types...>, T> {
static const std::size_t value = 1 + index_of<std::tuple<Types...>, T>::value;
};
template<class ListT> static const char constexpr * GetNameOfList(void) {
return NameList[index_of<ListTypes, ListT>::value];
}
int main() {
constexpr const char *value = GetNameOfList<BundlesList>();
std::cout << value << std::endl;
}
[live demo]

using enable_if with template specialization

I want to make function get_type_name. For types that belong to certain set example are numbers, geometry etc I want to make one get_type_name function which uses enable_if with type trait. And for each type that do not belong to particular set I want to specialize its own get_type_name function. This is my code and I get the following compiler error and can't figure out why:
error C2668: 'get_type_name': ambiguous call to overloaded function
could be 'std::string get_type_name(myenable_if::type
*)' or 'std::string get_type_name(void *)'
template<bool B, typename T = void>
struct myenable_if {};
template<typename T>
struct myenable_if<true, T> { typedef void type; };
template<class T>
struct is_number
{
static const bool value = false;
};
template<>
struct is_number<int>
{
static const bool value = true;
};
template<class T>
std::string get_type_name(void* v=0);
//get_type_name for specific type
template<>
std::string get_type_name<std::string>(void*)
{
return std::string("string");
}
//get_type_name for set of types
template<class T>
std::string get_type_name(typename myenable_if<is_number<T>::value>::type* t=0)
{
return std::string("number");
}
int main()
{
std::string n = get_type_name<int>();
}
Here is a working version.
#include <iostream>
#include <string>
#include <vector>
#include <iostream>
template<bool B, typename T = void>
struct myenable_if {};
template<typename T>
struct myenable_if<true, T> { typedef T type; };
template<class T>
struct is_number
{
static const bool value = false;
};
template<>
struct is_number<int>
{
static const bool value = true;
};
template<class T>
std::string get_type_name_helper(void* t, char)
{
return "normal";
}
template<class T>
typename myenable_if<is_number<T>::value, std::string>::type get_type_name_helper(void* t, int)
{
return "number";
}
//get_type_name for specific type
template<>
std::string get_type_name_helper<std::string>(void* t, char)
{
return std::string("string");
}
template <class T>
std::string get_type_name(void* t = 0)
{
return get_type_name_helper<T>(t, 0);
}
int main() {
std::string n = get_type_name<int>();
std::cout << n << '\n';
n = get_type_name<std::string>();
std::cout << n << '\n';
n = get_type_name<float>();
std::cout << n << '\n';
return 0;
}
See Live Demo

Boost fusion sequence type and name identification for structs and class

I am trying to use boost fusion for one of my projects and I an figuring out how to get type names and variable names for structures and classes.
#include <typeinfo>
#include <string>
#include <iostream>
#include <boost/fusion/include/sequence.hpp>
#include <boost/fusion/include/algorithm.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/adapt_adt.hpp>
#include <boost/lexical_cast.hpp>
using namespace boost::fusion;
struct Foo
{
int integer_value;
bool boolean_value;
};
class Bar
{
int integer_value;
bool boolean_value;
public:
Bar(int i_val, bool b_val):integer_value(i_val),boolean_value(b_val) {}
int get_integer_value() const { return integer_value; }
void set_integer_value(int i_val) { integer_value = i_val; }
bool get_boolean_value() const { return boolean_value; }
void set_boolean_value(bool b_val) { boolean_value = b_val; }
};
BOOST_FUSION_ADAPT_STRUCT(
Foo,
(int, integer_value)
(bool, boolean_value)
)
BOOST_FUSION_ADAPT_ADT(
Bar,
(int, int, obj.get_integer_value() , obj.set_integer_value(val))
(bool, bool, obj.get_boolean_value(), obj.set_boolean_value(val))
)
struct DisplayMembers
{
template <typename T>
void operator()(T& t) const {
std::cout << typeid(t).name() << " : " << boost::lexical_cast<std::string>(t) << std::endl;
}
};
int main(int argc, char *argv[])
{
struct Foo f = { 33, false};
for_each(f, DisplayMembers());
Bar b(34,true);
for_each(b, DisplayMembers());
return 0;
}
In the above example the result is
int : 33
bool : 0
struct boost::fusion::extension::adt_attribute_proxy<class Bar,0,0> : 34
struct boost::fusion::extension::adt_attribute_proxy<class Bar,1,0> : 1
I want the result as
int : integer_value : 33
bool : boolean_value : 0
int : integer_value : 34
bool : boolean_value : 1
I distilled the answer by sehe into something much simpler, provided you are using C++14
#include <iostream>
#include <boost/fusion/include/algorithm.hpp>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/mpl/range_c.hpp>
struct MyStruct {
std::string foo;
double bar;
};
BOOST_FUSION_ADAPT_STRUCT(MyStruct,
foo,
bar)
namespace fuz = boost::fusion;
namespace mpl = boost::mpl;
int main(int argc, char* argv[]) {
MyStruct dummy{"yo",3.14};
fuz::for_each(mpl::range_c<
unsigned, 0, fuz::result_of::size<MyStruct>::value>(),
[&](auto index){
std::cout << "Name: "
<< fuz::extension::struct_member_name<MyStruct,index>::call()
<< " Value: "
<< fuz::at_c<index>(dummy) << std::endl;
});
}
Outputs:
Name: foo Value: yo
Name: bar Value: 3.14
See it live on coliru
There's boost::fusion::extension::struct_member_name<S, N::value> to access the names.
Here's a generic fusion object visitor that I use:
namespace visitor {
template <typename Flavour, typename T> struct VisitorApplication;
namespace detail
{
template <typename V, typename Enable = void>
struct is_vector : boost::mpl::false_ { };
template <typename T>
struct is_vector<std::vector<T>, void> : boost::mpl::true_ { };
namespace iteration
{
// Iteration over a sequence
template <typename FusionVisitorConcept, typename S, typename N>
struct members_impl
{
// Type of the current member
typedef typename boost::fusion::result_of::value_at<S, N>::type current_t;
typedef typename boost::mpl::next<N>::type next_t;
typedef boost::fusion::extension::struct_member_name<S, N::value> name_t;
static inline void handle(FusionVisitorConcept& visitor, const S& s)
{
visitor.start_member(name_t::call());
VisitorApplication<FusionVisitorConcept, current_t>::handle(visitor, boost::fusion::at<N>(s));
visitor.finish_member(name_t::call());
members_impl<FusionVisitorConcept, S, next_t>::handle(visitor, s);
}
};
// End condition of sequence iteration
template <typename FusionVisitorConcept, typename S>
struct members_impl<FusionVisitorConcept, S, typename boost::fusion::result_of::size<S>::type>
{
static inline void handle(FusionVisitorConcept const&, const S&) { /*Nothing to do*/ }
};
// Iterate over struct/sequence. Base template
template <typename FusionVisitorConcept, typename S>
struct Struct : members_impl<FusionVisitorConcept, S, boost::mpl::int_<0>> {};
} // iteration
template <typename FusionVisitorConcept, typename T>
struct array_application
{
typedef array_application<FusionVisitorConcept, T> type;
typedef typename T::value_type value_type;
static inline void handle(FusionVisitorConcept& visitor, const T& t)
{
visitor.empty_array();
for (auto& el : t)
VisitorApplication<FusionVisitorConcept, value_type>::handle(visitor, el);
}
};
template <typename FusionVisitorConcept, typename T>
struct struct_application
{
typedef struct_application<FusionVisitorConcept, T> type;
static inline void handle(FusionVisitorConcept& visitor, const T& t)
{
visitor.empty_object();
iteration::Struct<FusionVisitorConcept, T>::handle(visitor, t);
}
};
template <typename FusionVisitorConcept, typename T, typename Enable = void>
struct value_application
{
typedef value_application<FusionVisitorConcept, T> type;
static inline void handle(FusionVisitorConcept& visitor, const T& t) {
visitor.value(t);
}
};
template <typename FusionVisitorConcept, typename T>
struct value_application<FusionVisitorConcept, boost::optional<T> >
{
typedef value_application<FusionVisitorConcept, boost::optional<T> > type;
static inline void handle(FusionVisitorConcept& visitor, const boost::optional<T>& t) {
if (t)
VisitorApplication<FusionVisitorConcept, T>::handle(visitor, *t);
else
; // perhaps some default action?
}
};
template <typename FusionVisitorConcept, typename T>
struct select_application
{
typedef
//typename boost::mpl::eval_if<boost::is_array<T>, boost::mpl::identity<array_application<FusionVisitorConcept, T>>,
typename boost::mpl::eval_if<detail::is_vector<T>, boost::mpl::identity<array_application <FusionVisitorConcept, T>>,
typename boost::mpl::eval_if<boost::fusion::traits::is_sequence<T>, boost::mpl::identity<struct_application<FusionVisitorConcept, T>>,
boost::mpl::identity<value_application<FusionVisitorConcept, T>>
> >::type type;
};
} // detail
template <typename FusionVisitorConcept, typename T>
struct VisitorApplication : public detail::select_application<FusionVisitorConcept, T>::type
{
};
}
template <typename FusionVisitorConcept, typename T>
void apply_fusion_visitor(FusionVisitorConcept& visitor, T const& o)
{
visitor::VisitorApplication<FusionVisitorConcept, T>::handle(visitor, o);
}
You can use it by supplying a visitor, e.g. for xml-like output:
struct DisplayMemberVisitor {
typedef std::string result_type;
DisplayMemberVisitor() { ss << std::boolalpha; }
std::string complete() { return ss.str(); }
void start_member (const char* name) {
ss << "<" << name << ">";
}
void finish_member(const char* name) {
ss << "</" << name << ">";
}
template <typename T> void value(T const& value) {
ss << value;
}
void empty_object() { }
void empty_array() { }
private:
std::stringstream ss;
};
See it Live On Coliru where (including some debug output) it prints:
<integer_value>33</integer_value><boolean_value>false</boolean_value><integer_value>34</integer_value><boolean_value>true</boolean_value>
Note that the ADT adaptation macro doesn't include a name (because none is available). You can probably quite easily make a macro FUSION_ADAPT_KEYD_ADT that also accepts a name and generates the relevant specializations of boost::fusion::extension::struct_member_name.
BONUS MATERIAL
Adding member name traits to ADT adapted members
Here's a simplistic approach that shows what little amount of work needs to be done.
#define MY_ADT_MEMBER_NAME(CLASSNAME, IDX, MEMBERNAME) \
namespace boost { namespace fusion { namespace extension { \
template <> struct struct_member_name<CLASSNAME, IDX> { typedef char const *type; static type call() { return #MEMBERNAME; } \
}; } } }
MY_ADT_MEMBER_NAME(Bar, 0, integer_value)
MY_ADT_MEMBER_NAME(Bar, 1, boolean_value)
This defines a macro to avoid most of the repetition. If you are a BOOST_PP whizkid you could somehow weave this into an adt_ex.hpp¹ header of sorts, so you could instead say:
BOOST_FUSION_ADAPT_ADT(Bar, // NOTE THIS PSEUDO-CODE
(integer_value, int, int, obj.get_integer_value(), obj.set_integer_value(val))
(boolean_value, bool, bool, obj.get_boolean_value(), obj.set_boolean_value(val)))
For now here's the ADT adapted trick Live On Coliru
¹ in case you're interested, here's a tarball of a prepared adt_ex tree (drop in alongsize adt.hpp): adt_ex.tgz as a starting point. It's just adt* but with macros and header guards renamed to adt_ex*

How do I determine if a type is callable with only const references?

I want to write a C++ metafunction is_callable<F, Arg> that defines value to be true, if and only if the type F has the function call operator of the form SomeReturnType operator()(const Arg &). For example, in the following case
struct foo {
void operator(const int &) {}
};
I want is_callable<foo, int &> to be false and is_callable<foo, const int &> to be true. This is what I have so far :
#include <memory>
#include <iostream>
template<typename F, typename Arg>
struct is_callable {
private:
template<typename>
static char (&test(...))[2];
template<unsigned>
struct helper {
typedef void *type;
};
template<typename UVisitor>
static char test(
typename helper<
sizeof(std::declval<UVisitor>()(std::declval<Arg>()), 0)
>::type
);
public:
static const bool value = (sizeof(test<F>(0)) == sizeof(char));
};
struct foo {
void operator()(const int &) {}
};
using namespace std;
int main(void)
{
cout << is_callable<foo, int &>::value << "\n";
cout << is_callable<foo, const int &>::value << "\n";
return 0;
}
This prints 1 and 1, but I want 0 and 1 because foo only defines void operator()(const int &).
After hours of playing around and some serious discussions in the C++ chat room, we finally got a version that works for functors with possibly overloaded or inherited operator() and for function pointers, based on #KerrekSB's and #BenVoigt's versions.
#include <utility>
#include <type_traits>
template <typename F, typename... Args>
class Callable{
static int tester[1];
typedef char yes;
typedef yes (&no)[2];
template <typename G, typename... Brgs, typename C>
static typename std::enable_if<!std::is_same<G,C>::value, char>::type
sfinae(decltype(std::declval<G>()(std::declval<Brgs>()...)) (C::*pfn)(Brgs...));
template <typename G, typename... Brgs, typename C>
static typename std::enable_if<!std::is_same<G,C>::value, char>::type
sfinae(decltype(std::declval<G>()(std::declval<Brgs>()...)) (C::*pfn)(Brgs...) const);
template <typename G, typename... Brgs>
static char sfinae(decltype(std::declval<G>()(std::declval<Brgs>()...)) (G::*pfn)(Brgs...));
template <typename G, typename... Brgs>
static char sfinae(decltype(std::declval<G>()(std::declval<Brgs>()...)) (G::*pfn)(Brgs...) const);
template <typename G, typename... Brgs>
static yes test(int (&a)[sizeof(sfinae<G,Brgs...>(&G::operator()))]);
template <typename G, typename... Brgs>
static no test(...);
public:
static bool const value = sizeof(test<F, Args...>(tester)) == sizeof(yes);
};
template<class R, class... Args>
struct Helper{ R operator()(Args...); };
template<typename R, typename... FArgs, typename... Args>
class Callable<R(*)(FArgs...), Args...>
: public Callable<Helper<R, FArgs...>, Args...>{};
Live example on Ideone. Note that the two failing tests are overloaded operator() tests. This is a GCC bug with variadic templates, already fixed in GCC 4.7. Clang 3.1 also reports all tests as passed.
If you want operator() with default arguments to fail, there is a possible way to do that, however some other tests will start failing at that point and I found it as too much hassle to try and correct that.
Edit: As #Johannes correctly notes in the comment, we got a little inconsistency in here, namely that functors which define a conversion to function pointer will not be detected as "callable". This is, imho, pretty non-trivial to fix, as such I won't bother with it (for now). If you absolutely need this trait, well, leave a comment and I'll see what I can do.
Now that all this has been said, IMHO, the idea for this trait is stupid. Why whould you have such exact requirements? Why would the standard is_callable not suffice?
(Yes, I think the idea is stupid. Yes, I still went and built this. Yes, it was fun, very much so. No, I'm not insane. Atleast that's what I believe...)
(with apologies to Kerrek for using his answer as a starting point)
EDIT: Updated to handle types without any operator() at all.
#include <utility>
template <typename F, typename Arg>
struct Callable
{
private:
static int tester[1];
typedef char yes;
typedef struct { char array[2]; } no;
template <typename G, typename Brg>
static char sfinae(decltype(std::declval<G>()(std::declval<Brg>())) (G::*pfn)(Brg)) { return 0; }
template <typename G, typename Brg>
static char sfinae(decltype(std::declval<G>()(std::declval<Brg>())) (G::*pfn)(Brg) const) { return 0; }
template <typename G, typename Brg>
static yes test(int (&a)[sizeof(sfinae<G,Brg>(&G::operator()))]);
template <typename G, typename Brg>
static no test(...);
public:
static bool const value = sizeof(test<F, Arg>(tester)) == sizeof(yes);
};
struct Foo
{
int operator()(int &) { return 1; }
};
struct Bar
{
int operator()(int const &) { return 2; }
};
struct Wazz
{
int operator()(int const &) const { return 3; }
};
struct Frob
{
int operator()(int &) { return 4; }
int operator()(int const &) const { return 5; }
};
struct Blip
{
template<typename T>
int operator()(T) { return 6; }
};
struct Boom
{
};
struct Zap
{
int operator()(int) { return 42; }
};
#include <iostream>
int main()
{
std::cout << "Foo(const int &): " << Callable<Foo, int const &>::value << std::endl
<< "Foo(int &): " << Callable<Foo, int &>::value << std::endl
<< "Bar(const int &): " << Callable<Bar, const int &>::value << std::endl
<< "Bar(int &): " << Callable<Bar, int &>::value << std::endl
<< "Zap(const int &): " << Callable<Zap , const int &>::value << std::endl
<< "Zap(int&): " << Callable<Zap , int &>::value << std::endl
<< "Wazz(const int &): " << Callable<Wazz, const int &>::value << std::endl
<< "Wazz(int &): " << Callable<Wazz, int &>::value << std::endl
<< "Frob(const int &): " << Callable<Frob, const int &>::value << std::endl
<< "Frob(int &): " << Callable<Frob, int &>::value << std::endl
<< "Blip(const int &): " << Callable<Blip, const int &>::value << std::endl
<< "Blip(int &): " << Callable<Blip, int &>::value << std::endl
<< "Boom(const int &): " << Callable<Boom, const int &>::value << std::endl
<< "Boom(int&): " << Callable<Boom, int &>::value << std::endl;
}
Demo: http://ideone.com/T3Iry
Here's something I hacked up which may or may not be what you need; it does seem to give true (false) for (const) int &...
#include <utility>
template <typename F, typename Arg>
struct Callable
{
private:
typedef char yes;
typedef struct { char array[2]; } no;
template <typename G, typename Brg>
static yes test(decltype(std::declval<G>()(std::declval<Brg>())) *);
template <typename G, typename Brg>
static no test(...);
public:
static bool const value = sizeof(test<F, Arg>(nullptr)) == sizeof(yes);
};
struct Foo
{
int operator()(int &) { return 1; }
// int operator()(int const &) const { return 2; } // enable and compare
};
#include <iostream>
int main()
{
std::cout << "Foo(const int &): " << Callable<Foo, int const &>::value << std::endl
<< "Foo(int &): " << Callable<Foo, int &>::value << std::endl
;
}
Something like this maybe? It's a bit round about to make it work on VS2010.
template<typename FPtr>
struct function_traits_impl;
template<typename R, typename A1>
struct function_traits_impl<R (*)(A1)>
{
typedef A1 arg1_type;
};
template<typename R, typename C, typename A1>
struct function_traits_impl<R (C::*)(A1)>
{
typedef A1 arg1_type;
};
template<typename R, typename C, typename A1>
struct function_traits_impl<R (C::*)(A1) const>
{
typedef A1 arg1_type;
};
template<typename T>
typename function_traits_impl<T>::arg1_type arg1_type_helper(T);
template<typename F>
struct function_traits
{
typedef decltype(arg1_type_helper(&F::operator())) arg1_type;
};
template<typename F, typename Arg>
struct is_callable : public std::is_same<typename function_traits<F>::arg1_type, const Arg&>
{
}
Here is a possible solution that utilizes an extra test to see if your template is being instantiated with a const T&:
#include <memory>
#include <iostream>
using namespace std;
template<typename F, typename Arg>
struct is_callable {
private:
template<typename>
static char (&test(...))[2];
template<bool, unsigned value>
struct helper {};
template<unsigned value>
struct helper<true, value> {
typedef void *type;
};
template<typename T>
struct is_const_ref {};
template<typename T>
struct is_const_ref<T&> {
static const bool value = false;
};
template<typename T>
struct is_const_ref<const T&> {
static const bool value = true;
};
template<typename UVisitor>
static char test(typename helper<is_const_ref<Arg>::value,
sizeof(std::declval<UVisitor>()(std::declval<Arg>()), 0)>::type);
public:
static const bool value = (sizeof(test<F>(0)) == sizeof(char));
};
struct foo {
void operator()(const int &) {}
};
int main(void)
{
cout << is_callable<foo, int &>::value << "\n";
cout << is_callable<foo, const int &>::value << "\n";
return 0;
}
Ran across this while doing something else, was able to adapt my code to fit. It has the same features (and limitations) as #Xeo, but does not need sizeof trick/enable_if. The default parameter takes the place of needing to do the enable_if to handle template functions. I tested it under g++ 4.7 and clang 3.2 using the same test code Xeo wrote up
#include <type_traits>
#include <functional>
namespace detail {
template<typename T, class Args, class Enable=void>
struct call_exact : std::false_type {};
template<class...Args> struct ARGS { typedef void type; };
template<class T, class ... Args, class C=T>
C * opclass(decltype(std::declval<T>()(std::declval<Args>()...)) (C::*)(Args...)) { }
template<class T, class ... Args, class C=T>
C * opclass(decltype(std::declval<T>()(std::declval<Args>()...)) (C::*)(Args...) const) { }
template<typename T, class ... Args>
struct call_exact<T, ARGS<Args...>,
typename ARGS<
decltype(std::declval<T&>()(std::declval<Args>()...)),
decltype(opclass<T, Args...>(&T::operator()))
>::type
> : std::true_type {};
}
template<class T, class ... Args>
struct Callable : detail::call_exact<T, detail::ARGS<Args...>> { };
template<typename R, typename... FArgs, typename... Args>
struct Callable<R(*)(FArgs...), Args...>
: Callable<std::function<R(FArgs...)>, Args...>{};

Deduce return type of operator/function for templates

Is something like this possible?
// We can even assume T and U are native C++ types
template<typename T, typename U>
magically_deduce_return_type_of(T * U) my_mul() { return T * U; }
Or would somebody have to hack up a return_type struct and specialize it for every pair of native types?
Heard of decltype?
In C++0x you can do
template<class T, class U>
auto mul(T x, U y) -> decltype(x*y)
{
return x*y;
}
You can do this in non C++0x code:
template<typename T, typename U> class Mul
{
T t_;
U u_;
public:
Mul(const T& t, const U& u): t_(t), u_(u) {}
template <class R>
operator R ()
{
return t_ * u_;
}
};
template<typename T, typename U>
Mul<T, U> mul(const T& t, const U& u)
{
return Mul<T, U>(t, u);
}
Usage:
char t = 3;
short u = 4;
int r = mul(t, u);
Here we have two type deductions. We implicitly declare return type by usage, not exactly decltype(T*U)
I'm using Visual Studio 2008, so I had to come up with a non C++0x way. I ended up doing something like this.
template<typename T> struct type_precedence { static const int value = -1; };
template< > struct type_precedence<long double> { static const int value = 0; };
template< > struct type_precedence<double> { static const int value = 1; };
template< > struct type_precedence<float> { static const int value = 2; };
template< > struct type_precedence<unsigned long long> { static const int value = 3; };
template< > struct type_precedence<long long> { static const int value = 4; };
template< > struct type_precedence<unsigned long> { static const int value = 5; };
template< > struct type_precedence<long> { static const int value = 6; };
template< > struct type_precedence<unsigned int> { static const int value = 7; };
template< > struct type_precedence<int> { static const int value = 8; };
template< > struct type_precedence<unsigned short> { static const int value = 9; };
template< > struct type_precedence<short> { static const int value = 10; };
template< > struct type_precedence<unsigned char> { static const int value = 11; };
template< > struct type_precedence<char> { static const int value = 12; };
template< > struct type_precedence<bool> { static const int value = 13; };
/////////////////////////////////////////////////////////////////////////////////////////
template<typename T, typename U, bool t_precedent = ((type_precedence<T>::value) <= (type_precedence<U>::value))>
struct precedent_type {
typedef T t;
};
template<typename T, typename U>
struct precedent_type<T,U,false> {
typedef U t;
};
/////////////////////////////////////////////////////////////////////////////////////////
template<typename T, typename U>
typename precedent_type<T,U>::t my_mul() { return T * U; }
EDIT: Here's the example - I'm actually doing this to multiply vectors. It looks something like this:
template<int N, typename T, typename U>
vec<N,typename precedent_type<T,U>::t> operator *(const vec<N,T>& v1,const vec<N,U>& v2) {
...
}
...
double3 = float3 * double3;
float4 = float4 * int4;
etc.
http://www2.research.att.com/~bs/C++0xFAQ.html#decltype
pre-C++0x
I don't know exactly what you want to accomplish, so:
template<typename T, typename U>
void my_mul(T t, U u, bool& overflow)
{
my_mul_impl(t*u, overflow);
}
template<typename TmultU>
void my_mul_impl(TmultU mult, bool& overflow)
{
//here you know the type and can do something meta-weird :)
if(mult > type_traits<TmultU>::max_allowed_in_my_cool_program())
overflow = true;
}
There is more