I'm developing a set of functions from an environment without not-full but high support for C++11 that are intented to be both callable with a multiple set of parameters but easy to pass to higher-level functions without having to force the user to force template parameter instantiations through casting, etc. So the most obvious solution to create these functions are by creating functors in the following way:
namespace mylib {
struct functor_f
{
return_type_1 operator()(type1, type2) const
{ return something; }
template<class Type3>
return_type_2 operator()(type1, type2, Type3) const
{ return something2; }
};
static auto functor = functor_f();
}
The problem with that approach is that, functor will have a different address per translation unit, which could cause problems depending on how the user will treat the functor. If I remove static, then I have to define functor in a .cpp module, and thus adding an invisible level of indirection for the compiler from other translation units, which I guess can cause an important efficiency penalty, since these functors are meant to be called thousands of times per algorithm (graph computations).
The most bizarre solution I can think of is to just forbid taking the address of the object, assuming the user doesn't even know the existence of std::address_of, by something like:
namespace mylib {
namespace _impl {
template<class...>
constexpr bool always_false() { return false; }
}
template<class T = void>
struct non_addressable
{
void operator&() const
{ static_assert(_impl::always_false<T>(), "Don't address me"); }
};
struct functor_f : non_addressable<>
{
return_type_1 operator()(type1, type2) const
{ return something; }
template<class Type3>
return_type_2 operator()(type1, type2, Type3) const
{ return something2; }
};
static auto functor = functor_f();
}
But I don't like it at all and I'm not fully sure about the side-effects of such a design.
There was any pre-C++14 idiom to achieve something like this? (simulating inline variables).
Aucun commentaire:
Enregistrer un commentaire