Templates and implicit conversion prevention on constructor - c++

I have a templated class Foo, which is of type T. When I create an instance of T I want to ensure the constructor is passed the same type.
The compiler ensures this, except for the small detail of implicit conversion. I want to prevent these and I can't figure out if there is a good way to do so. Compiler flags are not a option here.
I'm actually trying to prevent implicit conversions from double to float as my Foo class is doing some interesting magic that blows up on said cast. Any suggestions?
template <typename T>
class Foo {
public:
explicit Foo(const T& x) {kBitCount = sizeof(T); }
size_t kBitCount;
size_t mySize(){ return kBitCount; } // Size used to demonstrate
};
int main(int argc, char *argv[])
{
short sh = 5;
Foo<int> foo_int_from_short(sh); // I want this to fail
std::cout << "size:" << foo_int_from_short.mySize() << std::endl; // prints 4
Foo<short> foo_sh((unsigned int)5); // I want this to fail
std::cout << "size:" << foo_sh.mySize() << std::endl; // Prints 2
return 0;
}
Updated with solutions, C++11 allows for compile time checks
#include <limits>
#include <typeinfo>
#if __cplusplus > 199711L // If C++11 or greater
#include <type_traits>
#endif
template <typename T>
class Foo {
public:
#if __cplusplus > 199711L
// Prevent implict type conversions at compile time
template<
typename U,
typename = typename std::enable_if< std::is_same<U, T >::value >::type
>
explicit Foo(const U& x)
{
#else
template< typename U >
explicit Foo(const U& x)
{
// Assert on implict type conversions, run time
if(typeid(U).name() != typeid(T).name())
{
std::cerr << "You're doing an implicit conversion with Foo, Don't" << std::endl;
assert(typeid(U).name() == typeid(T).name()); // Or throw
}
#endif
}

How about adding an extra templated constructor to gather the less specialized calls:
template <typename T>
class Foo {
public:
template<typename U>
explicit Foo(const U& x); // Undefined reference error at link time
explicit Foo(const T& x) { kBitCount = sizeof(T); }
// ...
};
If you're using C++11, you don't have to create ugly undefined external errors either -- you can just use = delete:
template<typename U>
explicit Foo(const U& x) = delete;

This alternative to Cameron's solution has a single constructor that fails at compile time if an incorrect type is used:
template <typename T>
class Foo {
public:
template<
typename U,
typename = typename std::enable_if<std::is_same<U, T>{}>::type
>
explicit Foo(const U& x) { ... }
};
and could be made shorter with a couple of standard aliases.

Related

A compile time way to determine the least expensive argument type

I have a template that looks like this
template <typename T> class Foo
{
public:
Foo(const T& t) : _t(t) {}
private:
const T _t;
};
Is there a savvy template metaprogramming way to avoid using a const reference in cases where the argument type is trivial like a bool or char? like:
Foo(stl::smarter_argument<T>::type t) : _t(t) {}
I think the right type trait is is_scalar. This would work as follows:
template<class T, class = void>
struct smarter_argument{
using type = const T&;
};
template<class T>
struct smarter_argument<T, std::enable_if_t<std::is_scalar_v<T>>> {
using type = T;
};
Edit:
The above is still a bit old-school, thanks #HolyBlackCat for reminding me of this more terse version:
template<class T>
using smarter_argument_t = std::conditional_t<std::is_scalar_v<T>, T, const T&>;
I would suggest to use sizeof(size_t) (or sizeof(ptrdiff_t)) which returns a "typical" size related to your machine with the hope that any variable of this size fits into a register. In that case you can safely pass it by value. Moreover, as suggested by #n314159 (see comments at the end of this post) it is useful to ensure that the variable is also trivialy_copyable.
Here is a C++17 demo:
#include <array>
#include <ccomplex>
#include <iostream>
#include <type_traits>
template <typename T>
struct maybe_ref
{
using type = std::conditional_t<sizeof(T) <= sizeof(size_t) and
std::is_trivially_copyable_v<T>, T, const T&>;
};
template <typename T>
using maybe_ref_t = typename maybe_ref<T>::type;
template <typename T>
class Foo
{
public:
Foo(maybe_ref_t<T> t) : _t(t)
{
std::cout << "is reference ? " << std::boolalpha
<< std::is_reference_v<decltype(t)> << std::endl;
}
private:
const T _t;
};
int main()
{
// with my machine
Foo<std::array<double, 1>> a{std::array<double, 1>{}}; // <- by value
Foo<std::array<double, 2>> b{std::array<double, 2>{}}; // <- by ref
Foo<double> c{double{}}; // <- by value
Foo<std::complex<double>> d{std::complex<double>{}}; // <- by ref
}
I would make use of the C++20 keyword requires. Just like that:
#include <iostream>
template<typename T>
class Foo
{
public:
Foo(T t) requires std::is_scalar_v<T>: _t{t} { std::cout << "is scalar" <<std::endl; }
Foo(const T& t) requires (not std::is_scalar_v<T>): _t{t} { std::cout << "is not scalar" <<std::endl;}
private:
const T _t;
};
class cls {};
int main()
{
Foo{true};
Foo{'d'};
Foo{3.14159};
cls c;
Foo{c};
return 0;
}
You can run the code online to see the following output:
is scalar
is scalar
is scalar
is not scalar

template function overload in non-template class using SFINAE

TL;DR
A couple of templatized and overloaded non-templatized member functions in a non-templatized class should all end up routing through the same member function to perform the actual work. All the overloads and templatizations are done to convert the "data buffer" into gsl::span<std::byte> type (essentially a close relative to std::array<std::byte, N> from the Guidelines Support Library)
Wall of code
#include <array>
#include <cstdlib>
#include <iostream>
#pragma warning(push)
#pragma warning(disable: 4996)
#include <gsl.h>
#pragma warning(pop)
// convert PoD into "memory buffer" for physical I/O
// ignore endianness and padding/alignments for this example
template<class T> gsl::span<std::byte> byte_span(T& _x) {
return { reinterpret_cast<std::byte*>(&_x), sizeof(T) };
}
// implementation of physical I/O (not a functor, but tempting)
struct A {
enum class E1 : uint8_t { v1 = 10, v2, v3, v4 };
bool f(uint8_t _i1, gsl::span<std::byte> _buf = {}); // a - "in the end" they all call here
bool f(E1 _i1, gsl::span<std::byte> _buf = {}); // b
template<typename T, typename = std::enable_if_t< std::is_integral<T>::value > >
bool f(uint8_t _i1, T& _val); // c
template<typename T, typename = std::enable_if_t< std::is_integral<T>::value > >
bool f(E1 _i1, T& _val); // d
};
bool A::f(uint8_t _i1, gsl::span<std::byte> _buf)
{
std::cout << "f() uint8_t{" << (int)_i1 << "} with " << _buf.size() << " elements\n";
return true;
}
bool A::f(E1 _i1, gsl::span<std::byte> _buf)
{
std::cout << "f() E1{" << (int)_i1 << "} with " << _buf.size() << " elements\n\t";
return f((uint8_t)_i1, _buf);
}
template<class T, typename>
bool A::f(uint8_t _i1, T& _val)
{
std::cout << "template uint8_t\n\t";
return f(_i1, byte_span(_val));
}
template<class T, typename>
bool A::f(E1 _i1, T& _val)
{
std::cout << "template E1\n\t";
return f(_i1, byte_span(_val));
}
int main(){
A a = {};
std::array<std::byte, 1> buf;
long i = 2;
// regular function overloads
a.f(1, buf); // should call (a)
a.f(A::E1::v1, buf); // should call (b)
// template overloads
a.f(2, i); // should call (c)
a.f(A::E1::v2, i); // should call (d)
struct S { short i; };
// issue
//S s;
//a.f(3, s); // should call (c)
//a.f(A::E1::v3, s); // should call (d)
//// bonus - should use non-template overrides
//S sv[2] = {};
//a.f(5, sv); // should call (a)
//a.f(A::E1::v1, sv); // should call (b)
}
Details
The struct S is a PoD and it is tempting to change the template's enable_if to use the std::is_trivial or std::is_standard_layout. Unfortunately both these solutions "grab too much" and end up matching std::array (even if they do fix the compilation error of the //issue block).
The solution I have right now looks like a dead-end as my gut feeling is to start adding more template parameters and it seems to be getting very hairy very soon :(
Question
My goal is to achieve the following: use the class A's bool f() member function without too much syntactic overhead for any PoD (possibly including C arrays - see "bonus" in code) as shown in the body of main() and no runtime function call overhead for types that are auto-convertible to gsl::span (like std::array and std::vector).
Ideally...
I'd like to have a single templatized function per first parameter (either E1 or uint8_t) with multiple specializations listed outside the class's body to further reduce the perceived code clutter in the class's declaration and I can't figure out the way to properly do that. Something like the following (illegal C++ code below!):
struct A {
// ...
template<typename T> bool f(uint8_t _i1, T& _val);
template<typename T> bool f(E1 _i1, T& _val);
};
template<> bool f<is_PoD<T> && not_like_gsl_span<T>>(uint8_t /*...*/}
template<> bool f<is_PoD<T> && not_like_gsl_span<T>>(E1 /*...*/}
template<> bool f<is_like_gsl_span<T>>(uint8_t /*...*/}
template<> bool f<is_like_gsl_span<T>>(E1 /*...*/}
If this is not achievable I'd like to know why.
I'm on MSVC 2017 with C++17 enabled.
The first answer was a little wrong, for some reasons, I was totally confused by gsl. I thought it is something super specific. I am not using Guideline Support Library, though I have seen it and it looks good.
Fixed the code to properly work with gsl::span type.
struct A {
enum class E1 : uint8_t { v1 = 10, v2, v3, v4 };
private:
template <typename T>
static auto make_span(T& _x) ->
typename std::enable_if<std::is_convertible<T&, gsl::span<std::byte>>::value,
gsl::span<std::byte>>::type {
std::cout << "conversion" << std::endl;
return _x;
}
template <typename T>
static auto make_span(T& _x) ->
typename std::enable_if<!std::is_convertible<T&, gsl::span<std::byte>>::value,
gsl::span<std::byte>>::type {
std::cout << "cast" << std::endl;
return {reinterpret_cast<std::byte*>(&_x), sizeof(T)};
}
public:
template <typename T, typename U>
bool f(T _i, U& _buf) {
static_assert(
std::is_convertible<U&, gsl::span<std::byte>>::value || std::is_trivial<U>::value,
"The object must be either convertible to gsl::span<std::byte> or be of a trivial type");
const auto i = static_cast<uint8_t>(_i);
const auto span = make_span(_buf);
std::cout << "f() uint8_t{" << (int)i << "} with " << span.size() << " elements\n";
return true;
}
};

Could you please explain below code ? It compiles fine. Its related to check whether given class is base of another class [duplicate]

I want to get into more template meta-programming. I know that SFINAE stands for "substitution failure is not an error." But can someone show me a good use for SFINAE?
I like using SFINAE to check boolean conditions.
template<int I> void div(char(*)[I % 2 == 0] = 0) {
/* this is taken when I is even */
}
template<int I> void div(char(*)[I % 2 == 1] = 0) {
/* this is taken when I is odd */
}
It can be quite useful. For example, i used it to check whether an initializer list collected using operator comma is no longer than a fixed size
template<int N>
struct Vector {
template<int M>
Vector(MyInitList<M> const& i, char(*)[M <= N] = 0) { /* ... */ }
}
The list is only accepted when M is smaller than N, which means that the initializer list has not too many elements.
The syntax char(*)[C] means: Pointer to an array with element type char and size C. If C is false (0 here), then we get the invalid type char(*)[0], pointer to a zero sized array: SFINAE makes it so that the template will be ignored then.
Expressed with boost::enable_if, that looks like this
template<int N>
struct Vector {
template<int M>
Vector(MyInitList<M> const& i,
typename enable_if_c<(M <= N)>::type* = 0) { /* ... */ }
}
In practice, i often find the ability to check conditions a useful ability.
Heres one example (from here):
template<typename T>
class IsClassT {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template<typename C> static One test(int C::*);
// Will be chosen if T is anything except a class.
template<typename C> static Two test(...);
public:
enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
When IsClassT<int>::Yes is evaluated, 0 cannot be converted to int int::* because int is not a class, so it can't have a member pointer. If SFINAE didn't exist, then you would get a compiler error, something like '0 cannot be converted to member pointer for non-class type int'. Instead, it just uses the ... form which returns Two, and thus evaluates to false, int is not a class type.
In C++11 SFINAE tests have become much prettier. Here are a few examples of common uses:
Pick a function overload depending on traits
template<typename T>
std::enable_if_t<std::is_integral<T>::value> f(T t){
//integral version
}
template<typename T>
std::enable_if_t<std::is_floating_point<T>::value> f(T t){
//floating point version
}
Using a so called type sink idiom you can do pretty arbitrary tests on a type like checking if it has a member and if that member is of a certain type
//this goes in some header so you can use it everywhere
template<typename T>
struct TypeSink{
using Type = void;
};
template<typename T>
using TypeSinkT = typename TypeSink<T>::Type;
//use case
template<typename T, typename=void>
struct HasBarOfTypeInt : std::false_type{};
template<typename T>
struct HasBarOfTypeInt<T, TypeSinkT<decltype(std::declval<T&>().*(&T::bar))>> :
std::is_same<typename std::decay<decltype(std::declval<T&>().*(&T::bar))>::type,int>{};
struct S{
int bar;
};
struct K{
};
template<typename T, typename = TypeSinkT<decltype(&T::bar)>>
void print(T){
std::cout << "has bar" << std::endl;
}
void print(...){
std::cout << "no bar" << std::endl;
}
int main(){
print(S{});
print(K{});
std::cout << "bar is int: " << HasBarOfTypeInt<S>::value << std::endl;
}
Here is a live example: http://ideone.com/dHhyHE
I also recently wrote a whole section on SFINAE and tag dispatch in my blog (shameless plug but relevant) http://metaporky.blogspot.de/2014/08/part-7-static-dispatch-function.html
Note as of C++14 there is a std::void_t which is essentially the same as my TypeSink here.
Boost's enable_if library offers a nice clean interface for using SFINAE. One of my favorite usage examples is in the Boost.Iterator library. SFINAE is used to enable iterator type conversions.
Here's another (late) SFINAE example, based on Greg Rogers's answer:
template<typename T>
class IsClassT {
template<typename C> static bool test(int C::*) {return true;}
template<typename C> static bool test(...) {return false;}
public:
static bool value;
};
template<typename T>
bool IsClassT<T>::value=IsClassT<T>::test<T>(0);
In this way, you can check the value's value to see whether T is a class or not:
int main(void) {
std::cout << IsClassT<std::string>::value << std::endl; // true
std::cout << IsClassT<int>::value << std::endl; // false
return 0;
}
Examples provided by other answers seems to me more complicated than needed.
Here is the slightly easier to understand example from cppreference :
#include <iostream>
// this overload is always in the set of overloads
// ellipsis parameter has the lowest ranking for overload resolution
void test(...)
{
std::cout << "Catch-all overload called\n";
}
// this overload is added to the set of overloads if
// C is a reference-to-class type and F is a pointer to member function of C
template <class C, class F>
auto test(C c, F f) -> decltype((void)(c.*f)(), void())
{
std::cout << "Reference overload called\n";
}
// this overload is added to the set of overloads if
// C is a pointer-to-class type and F is a pointer to member function of C
template <class C, class F>
auto test(C c, F f) -> decltype((void)((c->*f)()), void())
{
std::cout << "Pointer overload called\n";
}
struct X { void f() {} };
int main(){
X x;
test( x, &X::f);
test(&x, &X::f);
test(42, 1337);
}
Output:
Reference overload called
Pointer overload called
Catch-all overload called
As you can see, in the third call of test, substitution fails without errors.
C++17 will probably provide a generic means to query for features. See N4502 for details, but as a self-contained example consider the following.
This part is the constant part, put it in a header.
// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf.
template <typename...>
using void_t = void;
// Primary template handles all types not supporting the operation.
template <typename, template <typename> class, typename = void_t<>>
struct detect : std::false_type {};
// Specialization recognizes/validates only types supporting the archetype.
template <typename T, template <typename> class Op>
struct detect<T, Op, void_t<Op<T>>> : std::true_type {};
The following example, taken from N4502, shows the usage:
// Archetypal expression for assignment operation.
template <typename T>
using assign_t = decltype(std::declval<T&>() = std::declval<T const &>())
// Trait corresponding to that archetype.
template <typename T>
using is_assignable = detect<T, assign_t>;
Compared to the other implementations, this one is fairly simple: a reduced set of tools (void_t and detect) suffices. Besides, it was reported (see N4502) that it is measurably more efficient (compile-time and compiler memory consumption) than previous approaches.
Here is a live example, which includes portability tweaks for GCC pre 5.1.
Here is one good article of SFINAE: An introduction to C++'s SFINAE concept: compile-time introspection of a class member.
Summary it as following:
/*
The compiler will try this overload since it's less generic than the variadic.
T will be replace by int which gives us void f(const int& t, int::iterator* b = nullptr);
int doesn't have an iterator sub-type, but the compiler doesn't throw a bunch of errors.
It simply tries the next overload.
*/
template <typename T> void f(const T& t, typename T::iterator* it = nullptr) { }
// The sink-hole.
void f(...) { }
f(1); // Calls void f(...) { }
template<bool B, class T = void> // Default template version.
struct enable_if {}; // This struct doesn't define "type" and the substitution will fail if you try to access it.
template<class T> // A specialisation used if the expression is true.
struct enable_if<true, T> { typedef T type; }; // This struct do have a "type" and won't fail on access.
template <class T> typename enable_if<hasSerialize<T>::value, std::string>::type serialize(const T& obj)
{
return obj.serialize();
}
template <class T> typename enable_if<!hasSerialize<T>::value, std::string>::type serialize(const T& obj)
{
return to_string(obj);
}
declval is an utility that gives you a "fake reference" to an object of a type that couldn't be easily construct. declval is really handy for our SFINAE constructions.
struct Default {
int foo() const {return 1;}
};
struct NonDefault {
NonDefault(const NonDefault&) {}
int foo() const {return 1;}
};
int main()
{
decltype(Default().foo()) n1 = 1; // int n1
// decltype(NonDefault().foo()) n2 = n1; // error: no default constructor
decltype(std::declval<NonDefault>().foo()) n2 = n1; // int n2
std::cout << "n2 = " << n2 << '\n';
}
The following code uses SFINAE to let compiler select an overload based on whether a type has certain method or not:
#include <iostream>
template<typename T>
void do_something(const T& value, decltype(value.get_int()) = 0) {
std::cout << "Int: " << value.get_int() << std::endl;
}
template<typename T>
void do_something(const T& value, decltype(value.get_float()) = 0) {
std::cout << "Float: " << value.get_float() << std::endl;
}
struct FloatItem {
float get_float() const {
return 1.0f;
}
};
struct IntItem {
int get_int() const {
return -1;
}
};
struct UniversalItem : public IntItem, public FloatItem {};
int main() {
do_something(FloatItem{});
do_something(IntItem{});
// the following fails because template substitution
// leads to ambiguity
// do_something(UniversalItem{});
return 0;
}
Output:
Float: 1
Int: -1
Here, I am using template function overloading (not directly SFINAE) to determine whether a pointer is a function or member class pointer: (Is possible to fix the iostream cout/cerr member function pointers being printed as 1 or true?)
https://godbolt.org/z/c2NmzR
#include<iostream>
template<typename Return, typename... Args>
constexpr bool is_function_pointer(Return(*pointer)(Args...)) {
return true;
}
template<typename Return, typename ClassType, typename... Args>
constexpr bool is_function_pointer(Return(ClassType::*pointer)(Args...)) {
return true;
}
template<typename... Args>
constexpr bool is_function_pointer(Args...) {
return false;
}
struct test_debugger { void var() {} };
void fun_void_void(){};
void fun_void_double(double d){};
double fun_double_double(double d){return d;}
int main(void) {
int* var;
std::cout << std::boolalpha;
std::cout << "0. " << is_function_pointer(var) << std::endl;
std::cout << "1. " << is_function_pointer(fun_void_void) << std::endl;
std::cout << "2. " << is_function_pointer(fun_void_double) << std::endl;
std::cout << "3. " << is_function_pointer(fun_double_double) << std::endl;
std::cout << "4. " << is_function_pointer(&test_debugger::var) << std::endl;
return 0;
}
Prints
0. false
1. true
2. true
3. true
4. true
As the code is, it could (depending on the compiler "good" will) generate a run time call to a function which will return true or false. If you would like to force the is_function_pointer(var) to evaluate at compile type (no function calls performed at run time), you can use the constexpr variable trick:
constexpr bool ispointer = is_function_pointer(var);
std::cout << "ispointer " << ispointer << std::endl;
By the C++ standard, all constexpr variables are guaranteed to be evaluated at compile time (Computing length of a C string at compile time. Is this really a constexpr?).

c++ template specialization for all subclasses

I need to create a template function like this:
template<typename T>
void foo(T a)
{
if (T is a subclass of class Bar)
do this
else
do something else
}
I can also imagine doing it using template specialization ... but I have never seen a template specialization for all subclasses of a superclass. I don't want to repeat specialization code for each subclass
You can do what you want but not how you are trying to do it! You can use std::enable_if together with std::is_base_of:
#include <iostream>
#include <utility>
#include <type_traits>
struct Bar { virtual ~Bar() {} };
struct Foo: Bar {};
struct Faz {};
template <typename T>
typename std::enable_if<std::is_base_of<Bar, T>::value>::type
foo(char const* type, T) {
std::cout << type << " is derived from Bar\n";
}
template <typename T>
typename std::enable_if<!std::is_base_of<Bar, T>::value>::type
foo(char const* type, T) {
std::cout << type << " is NOT derived from Bar\n";
}
int main()
{
foo("Foo", Foo());
foo("Faz", Faz());
}
Since this stuff gets more wide-spread, people have discussed having some sort of static if but so far it hasn't come into existance.
Both std::enable_if and std::is_base_of (declared in <type_traits>) are new in C++2011. If you need to compile with a C++2003 compiler you can either use their implementation from Boost (you need to change the namespace to boost and include "boost/utility.hpp" and "boost/enable_if.hpp" instead of the respective standard headers). Alternatively, if you can't use Boost, both of these class template can be implemented quite easily.
I would use std::is_base_of along with local class as :
#include <type_traits> //you must include this: C++11 solution!
template<typename T>
void foo(T a)
{
struct local
{
static void do_work(T & a, std::true_type const &)
{
//T is derived from Bar
}
static void do_work(T & a, std::false_type const &)
{
//T is not derived from Bar
}
};
local::do_work(a, std::is_base_of<Bar,T>());
}
Please note that std::is_base_of derives from std::integral_constant, so an object of former type can implicitly be converted into an object of latter type, which means std::is_base_of<Bar,T>() will convert into std::true_type or std::false_type depending upon the value of T. Also note that std::true_type and std::false_type are nothing but just typedefs, defined as:
typedef integral_constant<bool, true> true_type;
typedef integral_constant<bool, false> false_type;
I know this question has been answered but nobody mentioned that std::enable_if can be used as a second template parameter like this:
#include <type_traits>
class A {};
class B: public A {};
template<class T, typename std::enable_if<std::is_base_of<A, T>::value, int>::type = 0>
int foo(T t)
{
return 1;
}
I like this clear style:
void foo_detail(T a, const std::true_type&)
{
//do sub-class thing
}
void foo_detail(T a, const std::false_type&)
{
//do else
}
void foo(T a)
{
foo_detail(a, std::is_base_of<Bar, T>::value);
}
The problem is that indeed you cannot do something like this in C++17:
template<T>
struct convert_t {
static auto convert(T t) { /* err: no specialization */ }
}
template<T>
struct convert_t<T> {
// T should be subject to the constraint that it's a subclass of X
}
There are, however, two options to have the compiler select the correct method based on the class hierarchy involving tag dispatching and SFINAE.
Let's start with tag dispatching. The key here is that tag chosen is a pointer type. If B inherits from A, an overload with A* is selected for a value of type B*:
#include <iostream>
#include <type_traits>
struct type_to_convert {
type_to_convert(int i) : i(i) {};
type_to_convert(const type_to_convert&) = delete;
type_to_convert(type_to_convert&&) = delete;
int i;
};
struct X {
X(int i) : i(i) {};
X(const X &) = delete;
X(X &&) = delete;
public:
int i;
};
struct Y : X {
Y(int i) : X{i + 1} {}
};
struct A {};
template<typename>
static auto convert(const type_to_convert &t, int *) {
return t.i;
}
template<typename U>
static auto convert(const type_to_convert &t, X *) {
return U{t.i}; // will instantiate either X or a subtype
}
template<typename>
static auto convert(const type_to_convert &t, A *) {
return 42;
}
template<typename T /* requested type, though not necessarily gotten */>
static auto convert(const type_to_convert &t) {
return convert<T>(t, static_cast<T*>(nullptr));
}
int main() {
std::cout << convert<int>(type_to_convert{5}) << std::endl;
std::cout << convert<X>(type_to_convert{6}).i << std::endl;
std::cout << convert<Y>(type_to_convert{6}).i << std::endl;
std::cout << convert<A>(type_to_convert{-1}) << std::endl;
return 0;
}
Another option is to use SFINAE with enable_if. The key here is that while the snippet in the beginning of the question is invalid, this specialization isn't:
template<T, typename = void>
struct convert_t {
static auto convert(T t) { /* err: no specialization */ }
}
template<T>
struct convert_t<T, void> {
}
So our specializations can keep a fully generic first parameter as long we make sure only one of them is valid at any given point. For this, we need to fashion mutually exclusive conditions. Example:
template<typename T /* requested type, though not necessarily gotten */,
typename = void>
struct convert_t {
static auto convert(const type_to_convert &t) {
static_assert(!sizeof(T), "no conversion");
}
};
template<>
struct convert_t<int> {
static auto convert(const type_to_convert &t) {
return t.i;
}
};
template<typename T>
struct convert_t<T, std::enable_if_t<std::is_base_of_v<X, T>>> {
static auto convert(const type_to_convert &t) {
return T{t.i}; // will instantiate either X or a subtype
}
};
template<typename T>
struct convert_t<T, std::enable_if_t<std::is_base_of_v<A, T>>> {
static auto convert(const type_to_convert &t) {
return 42; // will instantiate either X or a subtype
}
};
template<typename T>
auto convert(const type_to_convert& t) {
return convert_t<T>::convert(t);
}
Note: the specific example in the text of the question can be solved with constexpr, though:
template<typename T>
void foo(T a) {
if constexpr(std::is_base_of_v<Bar, T>)
// do this
else
// do something else
}
If you are allowed to use C++20 concepts, all this becomes almost trivial:
template<typename T> concept IsChildOfX = std::is_base_of<X, T>::value;
// then...
template<IsChildOfX X>
void somefunc( X& x ) {...}

SFINAE: detect if class has free function

Is there a way, using SFINAE, to detect whether a free function is overloaded for a given class?
Basically, I’ve got the following solution:
struct has_no_f { };
struct has_f { };
void f(has_f const& x) { }
template <typename T>
enable_if<has_function<T, f>::value, int>::type call(T const&) {
std::cout << "has f" << std::endl;
}
template <typename T>
disable_if<has_function<T, f>::value, int>::type call(T const&) {
std::cout << "has no f" << std::endl;
}
int main() {
call(has_no_f()); // "has no f"
call(has_f()); // "has f"
}
Simply overloading call doesn’t work since there are actually a lot of foo and bar types and the call function has no knowledge of them (basically call is inside a and the users supply their own types).
I cannot use C++0x, and I need a working solution for all modern compilers.
Note: the solution to a similar question unfortunately doesn’t work here.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <functional>
#include <type_traits>
struct X {};
struct Y {};
__int8 f(X x) { return 0; }
__int16 f(...) { return 0; }
template <typename T> typename std::enable_if<sizeof(f(T())) == sizeof(__int8), int>::type call(T const& t) {
std::cout << "In call with f available";
f(t);
return 0;
}
template <typename T> typename std::enable_if<sizeof(f(T())) == sizeof(__int16), int>::type call(T const& t) {
std::cout << "In call without f available";
return 0;
}
int main() {
Y y; X x;
call(y);
call(x);
}
A quick modification of the return types of f() yields the traditional SFINAE solution.
If boost is allowed, the following code might meet your purpose:
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>
using namespace boost;
// user code
struct A {};
static void f( A const& ) {}
struct B {};
// code for has_f
static void f(...); // this function has to be a free standing one
template< class T >
struct has_f {
template< class U >
static char deduce( U(&)( T const& ) );
template< class U, class V >
static typename disable_if_c< is_same< V, T >::value, char(&)[2] >::type
deduce( U(&)( V const& ) );
static char (&deduce( ... ))[2];
static bool const value = (1 == sizeof deduce( f ));
};
int main()
{
cout<< has_f<A>::value <<endl;
cout<< has_f<B>::value <<endl;
}
However, there are severe restrictions.
The code assumes that all the user functions have the signature ( T const& ),
so ( T ) isn't allowed.
The function void f(...) in the above seems to need to be a free standing
function.
If the compiler enforces two phase look-up as expected normally, probably
all the user functions have to appear before the definition of has_f class
template.
Honestly, I'm not confident of the usefulness of the code, but anyway I hope
this helps.