Improve compile-time error messages in templated classes - c++

I have a templated class which is supposed to accepts some kind of containers (std::array and std::vector) of some kind of of objects (in this example string and doubles).
My goal is to provide some clear compilation error if the class is constructed from the wrong combination of objects.
The following code compiles in Visual Studio 17, version 15.9.0.
///Performing checks
namespace checks
{
template <typename T>
struct CorrectType {
enum { value = false };
};
template <>
struct CorrectType<std::string> {
enum { value = true };
};
template <>
struct CorrectType<double> {
enum { value = true };
};
template <typename T>
struct CorrectContainer {
enum { value = false };
};
template <typename T, typename A>
struct CorrectContainer<std::vector<T, A>> {
enum { value = CorrectType<T>::value };
};
template <typename T, std::size_t N>
struct CorrectContainer<std::array<T, N>> {
enum { value = CorrectType<T>::value };
};
template <class Container>
void constexpr check(){
static_assert(checks::CorrectContainer<Container>::value, "Wrong container: only vectors/arrays of doubles/strings are accepted");
}
}
template <typename Container>
class Wrapper
{
public:
explicit Wrapper(const Container &container) : container_(container), size_(container.size())
{
//type checking is performed
checks::check<Container>();
}
void display() const {
for (int i = 0; i < size_; i++)
std::cout << this->container_[i] << " ";
std::cout << std::endl;
}
private:
Container container_;
int size_ = 0;
};
int main()
{
//Ok
Wrapper array_wrapper(std::array<double, 5>{0.0,1.0,2.0,3.0,4.0});
array_wrapper.display();
//Ok
Wrapper string_wrapper(std::array<std::string, 3>{ "a","b","c" });
string_wrapper.display();
//Error - working as intended but not clear what went wrong
Wrapper<std::vector<int>> vector_wrapper({ 1,2,3});
vector_wrapper.display();
}
The code above works as intended, but the error is ambiguous: we are not able to understand if the container is wrong or the kind of object contained is. Moreover, if the templated object has not a size member function, it will fail too early.

As I understand your query, invalid type detection can probably be sketched out as
template<class> struct ValidType;
template<template<class...> class> struct ValidContainer: std::false_type {};
template<> struct ValidContainer<std::vector>: std::true_type {};
template<class> struct ValidType: std::false_type {};
template<class> struct ValidType<double>: std::true_type {};
template<class> struct ValidType<std::string>: std::true_type {};
template<class> struct ValidArgument {
static_assert(false, "Both container and element type are wrong");
};
template<template<class...> class Ctr, class T, class... Ts>
struct ValidArgument<Ctr<T, Ts...>> {
static_assert(ValidContainer<Ctr>::value || ValidType<T>::value
, "Both container and element type are wrong");
static_assert(ValidContainer<Ctr>::value, "Container type is wrong");
static_assert(ValidType<T>::value, "Element type is wrong");
};
template<class T, std::size_t n> struct ValidArgument<std::array<T, n>> {
static_assert(ValidType<T>::value, "Element type is wrong");
};
(Note this is not the real code, merely a demonstration of an idea.)
Arrays are still evil, in the sense that std::array has a non-type parameter, and thus you cannot have a single template that checks the container, the ultimate check is still for the kind 0-type, with container checking in generic case and std::array being treated separately.
Alternatively, ValidType can be slightly more compact:
template<class T> using ValidType = std::bool_constant<
std::is_same_v<T, double> || std::is_same_v<T, std::string>>;
Or
template<class T> using ValidType = std::disjunction<
std::is_same<T, double>, std::is_same<T, std::string>>;
Or a less-standard type matching class. For instance:
template<class T, class... Ts> inline constexpr bool is_one_of_v =
std::disjunction_v<std::is_same<T, Ts>...>;
template<class T> using ValidType =
std::bool_constant<is_one_of_v<T, double, std::string>>;
This way you're less likely to get rogue specializations later.

You might move your check inside class (and split your condition):
template <typename Container>
class Wrapper
{
static_assert(checks::CorrectContainer<Container>::value,
"only std::vector/std::array allowed");
static_assert(checks::CorrectType<typename Container::value_type>::value,
"only double and std::string");
public:
// ...
};
Demo

Related

Check if a type is the same as a templated type

I have a user defined class
template<typename T, int N>
class MyClass
{
// Implementation
};
and I want to check on the instantiation of another class if its template parameter is an instance of MyClass
template<typename T, std::enable_if_t<!is_MyClass<T>, bool> = true>
class MapClass
{
// custom stuff here
};
template<typename T, std::enable_if_t<is_MyClass<T>, bool> = true>
class MapClass
{
// Some more stuff here
};
I tried to implement it like this but my instantiation fails because it requires two parameters. How do I make automatically extract both parameters
template <typename T> struct is_MyClass : std::false_type {};
template <typename T, int N> struct is_MyClass<MyClass<T, N>> : std::true_type {};
Thanks
I suggest to write a trait is_instantiation_of_myClass that uses partial specialization:
template<typename T, int N>
class MyClass {};
template <typename C>
struct is_instantiation_of_myClass : std::false_type {};
template <typename T,int N>
struct is_instantiation_of_myClass<MyClass<T,N>> : std::true_type {};
template <typename C>
constexpr bool is_instantiation_of_myClass_v = is_instantiation_of_myClass<C>::value;
Now you can do SFINAE based on is_instantiation_of_myClass<T> or just plain specialization:
template <typename T,bool = is_instantiation_of_myClass_v<T>>
struct Foo;
template <typename T>
struct Foo<T,true> {
static constexpr bool value = true;
};
template <typename T>
struct Foo<T,false> {
static constexpr bool value = false;
};
int main() {
std::cout << Foo< int >::value << "\n";
std::cout << Foo< MyClass<int,42>>::value << "\n";
}
Live Demo

How to find maximum dereferenceable-level of the parameter T using template

I am designing a "dereferencer" class, for fun.
I wrote some structs and aliass :
template <class _T>
using deref_type = decltype(*std::declval<_T>());
template <class _T, class _SFINAE>
struct is_derefable : std::false_type {};
template <class _T>
struct is_derefable< _T, deref_type<_T> > : std::true_type
{
using return_type = deref_type<_T>;
};
template<class _T>
using check_derefable = is_derefable<T, deref_type<T>>;
and let's say that there is a variable with type T = std::vector<int**>::iterator, which is the iterator dereferenced into a level-2 pointer, thus has a 3-level dereferenceability.
Here, I want to know the maximum level of "dereferenceability" of an arbitrary type T, at the compile-time.
std::cout << deref_level<std::vector<int**>::iterator>::max << std::endl; // this should prints 3
I thought that it would be way similar to generating a sequence at the compile-time: Template tuple - calling a function on each element
, but I can't draw a concrete picture of it.
Here are what I've tried:
template<class _TF, class _T>
struct derefability {};
template<int _N, class _derefability>
struct deref_level;
template<int _N, class _T>
struct deref_level<_N, derefability<std::false_type, _T>>
{
static const int max = _N;
};
template<int _N, class _T>
struct deref_level<_N, derefability<std::true_type, _T>> :
deref_level<_N + 1, derefability<typename check_derefable<deref_type<_T>>::type, deref_type<_T>>>{};
deref_level<0, derefability<check_derefable<T>::type, T>::max;
but it does not work...(compiler says that max is not a member of tje class) What went wrong?
Here is a recursive implementation using SFINAE directly:
template <class T, class = void>
struct deref_level {
enum : std::size_t { value = 0 };
};
template <class T>
struct deref_level<T, decltype(void(*std::declval<T const &>()))> {
enum : std::size_t { value = deref_level<decltype(*std::declval<T const &>())>::value + 1 };
};
See it live on Wandbox
I don't know what went wrong with your template example, but here's an implementation using a recursive consteval function:
#include <type_traits>
template<typename T, int N = 0>
consteval int deref_level()
{
if constexpr (std::is_pointer<T>::value) {
typedef typename std::remove_pointer<T>::type U;
return deref_level<U, N + 1>();
} else {
return N;
}
}
int main() {
return deref_level<int****>(); // Returns 4
}
After a few days of work, I was able to write code that works without causing an error in MSVC13.
First of all, I needed a robust module to check the dereferenceability of the type.
Since the struct-level SFINAE check fails, I took another method that deduces the return type from overloaded functions with auto->decltype expression, based on the answer: link
template<class T>
struct is_dereferenceable
{
private:
template<class _type>
struct dereferenceable : std::true_type
{
using return_type = _type;
};
struct illegal_indirection : std::false_type
{
using return_type = void*;
};
template<class _type>
static auto dereference(int)->dereferenceable<
decltype(*std::declval<_type>())>;
template<class>
static auto dereference(bool)->illegal_indirection;
using dereferenced_result = decltype(dereference<T>(0));
public:
using return_type = typename dereferenced_result::return_type;
static const bool value = dereferenced_result::value;
};
Now I have a robust dereferenceability-checker, the remaining part becomes far easy.
template< class T,
class D = typename is_dereferenceable<T>::return_type >
struct dereferenceability;
template< class T >
struct dereferenceability<T, void*>
{
using level = std::integral_constant<int, 0>;
};
template< class T, class D >
struct dereferenceability<T, D&>
{
using level = std::integral_constant<int, dereferenceability<D>::level::value + 1>;
};
int main()
{
static_assert(dereferenceability<int>::level::value == 0, "something went wrong");
static_assert(dereferenceability<int****>::iterator>::level::value == 4, "something went wrong");
return 0;
}
I've tested codes above in Visual Studio 2013, and no error occured.

How do I declare SFINAE class?

Something is not working quite well for me. Is this the way to declare a class, that accepts only floating point template parameter?
template <typename T, swift::enable_if<std::is_floating_point<T>::value> = nullptr>
class my_float;
I fail to define methods outside this class. Doesn't compile, not sure why
Well... not exactly SFINAE... but maybe, using template specialization? Something as follows ?
template <typename T, bool = std::is_floating_point<T>::value>
class my_float;
template <typename T>
class my_float<T, true>
{
// ...
};
If you really want use SFINAE, you can write
template <typename T,
typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
class my_float
{
// ...
};
or also (observe the pointer there isn't in your example)
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr>
class my_float // ------------------------------------------------^
{
};
-- EDIT --
As suggested by Yakk (thanks!), you can mix SFINAE and template specialization to develop different version of your class for different groups of types.
By example, the following my_class
template <typename T, typename = void>
class my_class;
template <typename T>
class my_class<T,
typename std::enable_if<std::is_floating_point<T>::value>::type>
{
// ...
};
template <typename T>
class my_class<T,
typename std::enable_if<std::is_integral<T>::value>::type>
{
// ...
};
is developed for in two versions (two different partial specializations), the first one for floating point types, the second one for integral types. And can be easily extended.
You can also use static_assert to poison invalid types.
template <typename T>
class my_float {
static_assert(std::is_floating_point<T>::value,
"T is not a floating point type");
// . . .
};
It's a little bit more direct, in my opinion.
With either of the other approaches, e.g.
template <typename T, bool = std::is_floating_point<T>::value>
class my_float;
template <typename T> class my_float<T, true> { /* . . . */ };
my_float<int,true> is a valid type. I'm not saying that that's a bad approach, but if you want to avoid this, you'll have to encapsulate
my_float<typename,bool> within another template, to avoid exposing the bool template parameter.
indeed, something like this worked for me (thanks to SU3's answer).
template<typename T, bool B = false>
struct enable_if {};
template<typename T>
struct enable_if<T, true> {
static const bool value = true;
};
template<typename T, bool b = enable_if<T,is_allowed<T>::value>::value >
class Timer{ void start(); };
template<typename T, bool b>
void Timer<T,b>::start()
{ \* *** \*}
I am posting this answer because I did not want to use partial specialization, but only define the behavior of the class outside.
a complete workable example:
typedef std::integral_constant<bool, true> true_type;
typedef std::integral_constant<bool, false> false_type;
struct Time_unit {
};
struct time_unit_seconds : public Time_unit {
using type = std::chrono::seconds;
};
struct time_unit_micro : public Time_unit {
using type = std::chrono::microseconds;
};
template<typename T, bool B = false>
struct enable_if {
};
template<typename T>
struct enable_if<T, true> {
const static bool value = true;
};
template<typename T,
bool b = enable_if<T,
std::is_base_of<Time_unit,
T>::value
>::value>
struct Timer {
int start();
};
template<typename T, bool b>
int Timer<T, b>::start() { return 1; }
int main() {
Timer<time_unit_seconds> t;
Timer<time_unit_micro> t2;
// Timer<double> t3; does not work !
return 0;
}

How to design a serializable class such that any non-serialized attribute leads to a compile-time error?

Say you have the following code:
class A {
bool _attribute1;
};
// Arbitrarily using std::string, not the point of this question
std::string serialize(const A&);
Now a developer adds a new bool _attribute2 to class A and forgets to update the serialize function, which leads to a bug at runtime. (Already been there ?)
Is there a way to turn this issue into compile-time error ? As C++ doesn't support reflection, I have the feeling this is impossible, but I may be missing something.
If you are using c++1z you could make use of structured binding:
struct S {
bool b;
//bool c; // causes error
};
int main() {
S s;
auto [x] = s;
(void)x;
}
[live demo]
The following one should work with C++11.
A bit tricky indeed, it's based on a comment of #SamVarshavchik:
#include<cstddef>
#include<functional>
template<std::size_t> struct Int { int i; };
template<std::size_t> struct Char { char c; };
template<std::size_t> struct Bool { bool c; };
template<typename, template<std::size_t> class...>
struct Base;
template<template<std::size_t> class... T, std::size_t... I>
struct Base<std::index_sequence<I...>, T...>: T<I>... {};
template<template<std::size_t> class... T>
struct Check final: Base<std::make_index_sequence<sizeof...(T)>, T...> {};
class A final {
bool _attribute1;
bool _attribute2;
private:
char _attribute3;
// int _attribute4;
};
void serialize(const A &) {
static_assert(sizeof(A) == sizeof(Check<Bool, Bool, Char>), "!");
// do whatever you want here...
}
int main() {
serialize(A{});
}
The basic idea is to list all the types of the data members and define a new type from them with a mixin. Then it's a matter of putting a static_assert in the right place.
Note that private data members are taken in consideration too.
There exist some corner cases that could break it, but maybe it can work for your real code.
As a side note, it can be further simplified if C++14 is an option:
#include<cstddef>
template<typename... T>
constexpr std::size_t size() {
std::size_t s = 0;
std::size_t _[] = { s += sizeof(T)... };
(void)_;
return s;
}
class A final {
bool _attribute1;
bool _attribute2;
private:
char _attribute3;
// int _attribute4;
};
void serialize(const A &) {
static_assert(sizeof(A) == size<bool, bool, char>(), "!");
// ...
}
int main() {
serialize(A{});
}
If you are doomed to use c++11 and still you are interested in serializing only the public fields you could create trait testing if the type can be constructed using list initialization with a given parameters types but not even one more (of any type):
#include <type_traits>
struct default_param {
template <class T>
operator T();
};
template <class T, class...>
using typer = T;
template <class, class, class... Args>
struct cannot_one_more: std::true_type {};
template <class Tested, class... Args>
struct cannot_one_more<typer<void, decltype(Tested{std::declval<Args>()..., default_param{}})>, Tested, Args...>: std::false_type {
};
template <class...>
struct is_list_constructable: std::false_type {};
template <class Tested, class... Args>
struct is_list_constructable<Tested(Args...)>: is_list_constructable<void, Tested, Args...> { };
template <class Tested, class... Args>
struct is_list_constructable<typer<void, decltype(Tested{std::declval<Args>()...}), typename std::enable_if<cannot_one_more<void, Tested, Args...>::value>::type>, Tested, Args...>: std::true_type { };
struct S {
bool b;
//bool c; // causes error
};
int main() {
static_assert(is_list_constructable<S(bool)>::value, "!");
}
[live demo]

Howto check a type for the existence of parameterless operator()

I'm trying to check whether a functor is compatible with a given set of parametertypes and a given return type (that is, the given parametertypes can be implicitely converted to the actual parametertypes and the other way around for the return type). Currently I use the following code for this:
template<typename T, typename R, template<typename U, typename V> class Comparer>
struct check_type
{ enum {value = Comparer<T, R>::value}; };
template<typename T, typename Return, typename... Args>
struct is_functor_compatible
{
struct base: public T
{
using T::operator();
std::false_type operator()(...)const;
};
enum {value = check_type<decltype(std::declval<base>()(std::declval<Args>()...)), Return, std::is_convertible>::value};
};
check_type<T, V, Comparer>
This works quite nicely in the majority of cases, however it fails to compile when I'm testing parameterless functors like struct foo{ int operator()() const;};, beccause in that case the two operator() of base are apperently ambigous, leading to something like this:
error: call of '(is_functor_compatible<foo, void>::base) ()' is ambiguous
note: candidates are:
note: std::false_type is_functor_compatible<T, Return, Args>::base::operator()(...) const [with T = foo, Return = void, Args = {}, std::false_type = std::integral_constant<bool, false>]
note: int foo::operator()() const
So obvoiusly I need a different way to check this for parameterless functors. I tried making a partial specialization of is_functor_compatible for an empty parameterpack, where I check if the type of &T::operator() is a parameterless memberfunction, which works more or less. However this approach obviously fails when the tested functor has several operator().
Therefore my question is if there is a better way to test for the existence of a parameterless operator() and how to do it.
When I want to test if a given expression is valid for a type, I use a structure similar to this one:
template <typename T>
struct is_callable_without_parameters {
private:
template <typename T1>
static decltype(std::declval<T1>()(), void(), 0) test(int);
template <typename>
static void test(...);
public:
enum { value = !std::is_void<decltype(test<T>(0))>::value };
};
Have you tried something like:
template<size_t>
class Discrim
{
};
template<typename T>
std::true_type hasFunctionCallOper( T*, Discrim<sizeof(T()())>* );
template<typename T>
std::false_type hasFunctionCallOper( T*, ... );
After, you discriminate on the return type of
hasFunctionCallOper((T*)0, 0).
EDITED (thanks to the suggestion of R. Martinho Fernandes):
Here's the code that works:
template<size_t n>
class CallOpDiscrim {};
template<typename T>
TrueType hasCallOp( T*, CallOpDiscrim< sizeof( (*((T const*)0))(), 1 ) > const* );
template<typename T>
FalseType hasCallOp( T* ... );
template<typename T, bool hasCallOp>
class TestImpl;
template<typename T>
class TestImpl<T, false>
{
public:
void doTellIt() { std::cout << typeid(T).name() << " does not have operator()" << std::endl; }
};
template<typename T>
class TestImpl<T, true>
{
public:
void doTellIt() { std::cout << typeid(T).name() << " has operator()" << std::endl; }
};
template<typename T>
class Test : private TestImpl<T, sizeof(hasCallOp<T>(0, 0)) == sizeof(TrueType)>
{
public:
void tellIt() { this->doTellIt(); }
};