Limit allowed COM Interfaces by using template function with limited variadic parameters (std::is_same) - com

I have wrapper classes contaning COM pointers (or smart pointers) to different interfaces.
INTEND:
Some COM classes can be obtained from various other COM interfaces, and I want to make a template constructor with variadic types, which would allow passing arguments only of appropriate types.
something like:
template <class T, class = typename
std::enable_if<std::is_base_of<IUnknown, T>::value>::type, class ... Types>
class WithCOMptrbase
{
protected:
T* ptr_;
public:
//construct smart pointer by copy
WithCOMptrbase(T* ptr, bool AddRef = false)
: ptr_(ptr)
{
if (AddRef) ptr_->AddRef();
}
/*construct a smart pointer by querying an interface from an argument of
a type which is the same as one of the variadics*/
template <class TypeOther, class = typename
std::enable_if<syd::is_same<Types... , TypeOther>::value... ||
...>::type> /*there needs to be a proper version*/
WithCOMptrbase(TypeOther* ptr)
: ptr_(cQueryInterface<T>(ptr))
{}
//other methods
};
helper function:
template <class U, class = typename
std::enable_if<std::is_base_of<IUnknown, U>::value>::type>
T* cQueryInterface<T>(U *ptr)
{
T* out;
HRESULT hr = ptr->QueryInterface(__uuidof(T), (void**)&out);
if (!SUCCEEED(hr)) throw _com_error(hr);
return out;
}
Therefore, I will define my wrapper class
class WrapperClass : protected WithCOMptrbase<IThis, IInterface1, IInterface2, IInterface3>
{
//methods
};
So far I have found this thread:
How to make a variadic is_same?
but it is only about structs, not functions.
My goal is to limit the possibility of passing inapproprtiate Interface pointer, hence not to deal with wrong interface errors at runtime.
UPDATE:
Since Composition is preferable over inheritance, I've done some rethinking and decided to use a template function rather than a template class. So far I've managed to combine given answers and came up with this:
template <bool S, class Out, class Other, typename
std::enable_if<S>::type* = nullptr>
//copy-construct Smart Pointer for same Interfaces
WComPtr<Out> WFilterSame(const WComPtr<Other>& pOther)
{
return WComPtr<Out>(pOther);
}
template <bool S, class Out, class Other, typename
std::enable_if<!S>::type* = nullptr>
//Query Interface if differ
WComPtr<Out> WFilterSame(const WComPtr<Other>& pOther)
{
return pOther.QueryInterface<Out>();
}
template <class Out, class ... Permitted, class Other>
WComPtr<Out> WFilterComInterfPtr(const WComPtr<Other>& pOther)
{
static_assert(std::is_same<Out, Other>::value ||
(std::is_same<Permitted, Other>::value || ...),
"Interface is not supported.");
return WFilterSame<std::is_same<Out, Other>::value, Out>(pOther);
}
Now I can define a constructor of my COM wrapper class:
class WComClass
{
private:
WComPtr<Interface> pComPtr_; //My Smart COM pointer
template <class Other>
WComPtr<Interface> WFilter(const WComPtr<Other>& pOther)
{
return WFilterComInterfPtr<Interface, IAllowed1, IAllowed2>(pOther);
}
public:
template <class Other>
WComClass(const WComPtr<Other>& pOther)
: pComPtr_(WFilter(pOther))
{}
//methods
};
So far it behaved as intended (WFilterComInterfPtr), I don't expect it to fail in the wrapper class costructor.

Try with
template <class TypeOther, class =
std::enable_if_t<(std::is_same_v<Types, TypeOther> || ...)>>
WithCOMptrbase(TypeOther* ptr)
: ptr_(cQueryInterface<T>(ptr))
{}
I mean... you're using three ellipsis instead of one (remove the ellipsis after ::value and the one after Types) and you need an additional couple of parentheses.
Off topic: are you sure that works
template <class T, class ... Types, class = typename
std::enable_if<std::is_base_of<IUnknown, T>::value>::type>
class WithCOMptrbase
?
SFINAE through a default type after a variadic list?

How about CRTP to avoid some template:
template <typename Base, typename T>
class Impl
{
public:
Impl() = default;
explicit Impl(T*) { static_cast<Base*>(this)->ptr_ = cQueryInterface<T>(ptr); }
};
template <class T, class ... Ts>
class WithCOMptrbase : private Impl<WithCOMptrbase<T, Ts...>, Ts>...
{
static_assert(std::is_base_of<IUnknown, T>::value);
static_assert((std::is_base_of<IUnknown, Ts>::value && ...));
template <typename, typename> friend struct Impl; // We don't have variadic friend :/
protected:
T* ptr_ = nullptr;
public:
using Impl<WithCOMptrbase, Ts>::Impl...;
//construct smart pointer by copy
explicit WithCOMptrbase(T* ptr, bool AddRef = false) : ptr_(ptr)
{
if (AddRef) ptr_->AddRef();
}
//other methods
};

Related

Dart : Why should overriding method's parameter be "wider" than parent's one? (probably topic about Contravariant) Part2

https://dart.dev/guides/language/language-tour#extending-a-class
Argument types must be the same type as (or a supertype of) the
overridden method’s argument types. In the preceding example, the
contrast setter of SmartTelevision changes the argument type from int
to a supertype, num.
I was looking at the above explanation and wondering why the arguments of subtype member methods need to be defined more "widely"(generally) than the original class's one.
https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Function_types
class AnimalShelter {
Animal getAnimalForAdoption() {
// ...
}
void putAnimal(Animal animal) {
//...
}
}
class CatShelter extends AnimalShelter {
//↓ Definitions that are desirable in the commentary
void putAnimal(Object animal) {
// ...
}
//↓Definitions that are not desirable in the commentary
void putAnimal(Cat animal) {
// ...
}
//I can't understand why this definition is risky.
//What specific problems can occur?
}
I think this wikipedia sample code is very easy to understand, so what kind of specific problem (fault) can occur if the argument of the member method of the subtype is defined as a more "narrower"(specific) type?
Even if it is explained in natural language, it will be abstract after all, so it would be very helpful if you could give me a complete working code and an explanation using it.
Let's consider an example where you have a class hierarchy:
Animal
/ \
Mammal Reptile
/ \
Dog Cat
with superclasses (wider types) above subclasses (narrower types).
Now suppose you have classes:
class Base {
void takeObject(Mammal mammal) {
// ...
}
Mammal returnObject() {
// ...
}
}
class Derived extends Base {
// ...
}
The public members of a class specify an interface: a contract to the callers. In this case, the Base class advertises a takeObject method that accepts any Mammal argument. Every instance of a Base class thus is expected to conform to this interface.
Following the Liskov substitution principle, because Derived extends Base, a Derived instance is a Base, and therefore it too must conform to that same Base class interface: its takeObject method also must accept any Mammal argument.
If Derived overrode takeObject to accept only Dog arguments:
class Derived extends Base {
#override
void takeObject(Dog mammal) { // ERROR
// ...
}
}
that would violate the contract from the Base class's interface. Derived's override of takeObject could be invoked with a Cat argument, which should be allowed according to the interface declared by Base. Since this is unsafe, Dart's static type system normally prevents you from doing that. (An exception is if you add the covariant keyword to disable type-safety and indicate that you personally guarantee that Derived.takeObject will never be called with any Mammals that aren't Dogs. If that claim is wrong, you will end up with a runtime error.)
Note that it'd be okay if Derived overrode takeObject to accept an Animal argument instead:
class Derived extends Base {
#override
void takeObject(Animal mammal) { // OK
// ...
}
}
because that would still conform to the contract of Base.takeObject: it's safe to call Derived.takeObject with any Mammal since all Mammals are also Animals.
Note that the behavior for return values is the opposite: it's okay for an overridden method to return a narrower type, but returning a wider type would violate the contract of the Base interface. For example:
class Derived extends Base {
#override
Dog returnObject() { // OK, a `Dog` is a `Mammal`, as required by `Base`
// ...
}
}
but:
class Derived extends Base {
#override
Animal returnObject() { // ERROR: Could return a `Reptile`, which is not a `Mammal`
// ...
}
}
void main(){
Animal a1 = Animal();
Cat c1 = Cat();
Dog d1 = Dog();
AnimalCage ac1 = AnimalCage();
CatCage cc1 = CatCage();
AnimalCage ac2 = CatCage();
ac2.setAnimal(d1);
//cc1.setAnimal(d1);
}
class AnimalCage{
Animal? _animal;
void setAnimal(Animal animal){
print('animals setter');
_animal = animal;
}
}
class CatCage extends AnimalCage{
Cat? _cat;
#override
void setAnimal(covariant Cat animal){
print('cats setter');
_cat = animal;
/*
if(animal is Cat){
_cat = animal;
}else{
print('$animal is not Cat!');
}
*/
}
}
class Animal {}
class Cat extends Animal{}
class Dog extends Animal{}
Unhandled Exception: type 'Dog' is not a subtype of type 'Cat' of 'animal'
In the above code, even if the setAnimal method receives a Dog instance, a compile error does not occur and a runtime error occurs, so making the parameter the same type as the superclass's one and checking the type inside the method is necessary.

JUnit 5 and Arguments.of() with functions

Writing a JUnit 5 parameterized test and need to pass functions to the test using Arguments.of(), but there are 2 compile errors that I don't know how to fix. Any help would be appreciated.
The method of(Object...) in the type Arguments is not applicable for the arguments (boolean, String::length)
The target type of this expression must be a functional interface
public static Stream<Arguments> some() {
return Stream.of(Arguments.of(true, String::length));
}
#ParameterizedTest
#MethodSource
public <T> void some(final T input, final Function<String, Integer> length) {
}
The following works as expected.
public void sample() {
some(true, String::length);
}
Wrap the arguments in a helper method
Similar to the answer "wrap it in a class", but possibly less intrusive, is to use a helper method to pass the functional interface as a java.lang.Object.
For example, the first raw method reference, Math::ciel, in this parameterized test:
#ParameterizedTest
#MethodSource("testCases")
void shouldExerciseMethod(Function<Double, Double> method, Double expected) {
assertEquals(expected, method.apply(1.5d), 1.0E-8d);
}
static Stream<Arguments> testCases() {
return Stream.of(Arguments.of(Math::ceil, 2.0d),
Arguments.of(Math::floor, 1.0d));
}
causes this compilation error:
java: method of in interface org.junit.jupiter.params.provider.Arguments cannot be applied to given types;
required: java.lang.Object[]
found: Math::ceil,double
reason: varargs mismatch; java.lang.Object is not a functional interface
which you can get around by passing the arguments through a helper method:
static <T, U> Arguments args(Function<T, U> method, U expected) {
return Arguments.of(method, expected);
}
so:
static Stream<Arguments> testCases() {
return Stream.of(args(Math::ceil, 2.0d),
args(Math::floor, 1.0d));
}
My attempts to make the idiom more general using varargs failed with variations on the same error, so I have ended up overloading it whenever I need another signature.
The function needs to be wrapped in a class.
public static class P {
private final Function<String, Integer> mFunction;
public P(final Function<String, Integer> function) {
mFunction = function;
}
public Function<String, Integer> function() {
return mFunction;
}
}
public static Stream<Arguments> some() {
return Stream.of(Arguments.of(3, "abc", new P(String::length)));
}
#ParameterizedTest
#MethodSource
public <T> void some(final int expect, final String input, final P p) {
assertEquals(expect, p.function().apply(input));
}
I liked #adrian-redgers solution, but I think overloading a method for each signature needed is a bit overkill.
You only really need to convert the functional interface to an object. So the solution I implemented was:
/**
* Helps to use {#link org.junit.jupiter.params.provider.Arguments#of(Object...)}, as functional
* interfaces cannot be converted into an object directly.
*/
public class ArgumentsWrapper {
private ArgumentsWrapper() {
throw new IllegalStateException(
ArgumentsWrapper.class + " util class cannot be instantiated");
}
public static <T, U> Function<T, U> wrap(Function<T, U> function) {
return function;
}
}
Then, it can be used as:
public static Stream<Arguments> testMapAlarmTypeConfigWithLanguage() {
return Stream.of(
// Statically imported ArgumentsWrapper#wrap
Arguments.of(null, wrap(AlarmTypeConfig::getNameInEnglish)),
Arguments.of("en-us", wrap(AlarmTypeConfig::getNameInEnglish)),
Arguments.of("es-es", wrap(AlarmTypeConfig::getNameInSpanish)));
}

OOP - How to create an interface in Reason

Let's say I have the following abstractProductA class with a public method called methodA :
class abstractProductA = {
pub methodA => "name";
};
I would like to create an interface that says function methodA should always return a string. Something similar to
interface abstractProductA {
abstractProductA(): string
}
only in reason, and then have class implement it. Any suggestions are more than welcome. Thank you
What you're really asking for it seems is how to define and use an abstract class, which is called a virtual class in OCaml/Reason:
class virtual virtualProductA = {
pub virtual methodA: string;
};
class abstractProductA = {
inherit virtualProductA;
pub methodA = "name";
};
An interface is more for consumers to abstract away an implementation, and while a virtual class can be used as an interface by itself, since OCaml/Reason objects are structurally typed you can also just specify the object type you need. And of course you can bind it to a name if you like:
type interfaceA = {.
methodA : string
};
let f (p: interfaceA) => Js.log p#methodA;
f (new abstractProductA);

How to call constructor in php?

If I create a class and define a public constructor of it and I also create a child class of the parent class, it also have constructor.
Then how can I call these two constructors from one of the method of subclass? I mean how to call two or more constructor from one method of a child class in php?
In C++:
You can call just by creating a child object.
When you just create a child object it first calls Parent Constructor and then The child Constructor.
Example:
Class Parent {
void Parent :: Parent() {
cout << "I am parent Constructor!" << endl;
}
};
Class Child : Public Parent() {
void Child :: Child() {
cout << "I am Child Constructor" << endl;
}
};
int main() {
Child childobj;
}
Output:
"I am parent Constructor!"
"I am Child Constructor"
For PHP
class Parent {
public function __construct($bypass = false) {
// Only perform actions inside if not bypassing.
if (!$bypass) {
}
}
}
class Child extends Parent {
public function __construct() {
$bypassPapa = true;
parent::__construct($bypassPapa);
}
}
I am answering this based specifically on C++ programming, as I am not certain which OOP language you are using, but I expect that the principles, if not the specific syntax, will apply.
When you define a class with at least one constructor, the compiler will not generate an implicit constructor. As such, if the constructor(s) you define for the base class require parameters, they must be included in a specific call from the constructor in the child class since there will be no parameter free constructor to call.
class Parent
{
public:
Parent(int a,int a)
:a(a),
b(b)
{
cout<<"Parent constructor "<<a<<b;
}
~Parent()
{}
private:
int a;
int b;
};
class Child : public Parent
{
public:
Child()
:c(5) //error: implicit constructor for Parent is not found
{
cout<<"Child constructor "<<c;
}
~Child()
{}
private:
int c;
};
int main()
{
Child x;
return 0;
}
This problem can be corrected by including a call to the Parent constructor within the constructor for the Child class as follows:
.
.
.
Child()
:Parent(3,4), // Explicit call to Parent constructor
c(5)
{
cout<<"Child constructor "<<c;
}
.
.
.
Hope this helps.
In C#;
When you create an instance of subclass, if the base class has a parameter-less constructor, It will be called. But if the base class has parameter constructor, you may call the constructor of that by following syntax.
Class SubClass : BaseClass(...)
{
...
}
In order to call constructor in other methods you need to have a protected method which was called by constructor, then you can call it from another method. Please note that you cannot call constructor from another method because it's a mechanism for instantiating (It should be called when an instance of that type is created)

C++ / CLI cannot access protected member of base class

I have this class:
ref class Wrapper {
protected:
Native *pn;
public:
Wrapper(int val) { pn = new Native( val ); }
};
Then I derive from it:
ref class DerivedWrapper : public Wrapper{
public:
DerivedWrapper(int val) {pn = new DerivedNative(val); }
}
The compiler complains:
error C2248 ‘ Wrapper::pn’ : cannot access private member declared in class ‘Wrapper’
The base class native pointer is clearly protected, and the derived class should have ready access to it. All my instincts tell me this should work. Is there something peculiar to ref classes?
I’m compiling with VS 2008 SP 1
The native type in your case has to have public or protected accessibility in the compiled assembly itself. There is a special make_public pragma directive that can promote the native type. Add this to the code:
#pragma make_public(Native)
The make_public pragma is documented at http://msdn.microsoft.com/en-us/library/ms235607.aspx
Consider initializing pn in a constructor of Wrapper, or you need to provide default constructor for your Wrapper. Don't forget 'public' in the ref class definition.
public ref class Wrapper {
protected:
Native *pn;
Wrapper(Native * fpn):pn(fpn)
{}
public:
Wrapper(int val) { pn = new Native( val ); }
};
ref class DerivedWrapper : public Wrapper{
public:
DerivedWrapper(int val):Wrapper(new DerivedNative(val)){}
};