How to declare static field in class - windows-phone-8

I have a XAML + DirectX app and I want to add static field to my "interop" class:
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Direct3DInterop sealed : public Windows::Phone::Input::Interop::IDrawingSurfaceManipulationHandler
{
public:
static int VALUE = 0;
...
};
It does not compile saying "only static const integral data members can be initialized within a class".
If I change it to const static int VALUE = 0; then it still does not compile with error "a non-value type cannot have any public data members"
What am I doing wrong?

WinRT public classes have a number of limitations to ensure they are consumable by multiple languages including C++, JavaScript, and C#. This is why you are getting error C3984. You can't have public fields and instead must use properties. You'd make it a read-only property:
property int VALUE
{
int get() { return 0; }
}
It is important to remember that properties are function calls and can't usually be optimized away, so you should consider that when designing the interfaces.
If you intend to have this class only consumable by C++, consider not using a WinRT class and instead use a simple C++ class which you managed the lifetime using std::unique_ptr or std::shared_ptr. In that case, you can of course use the public field approach as always.
The original problem you got is a general C++ language restriction not specific to WinRT. Error C2864 (you are using VS 2012 from the text you posted) is a little more general with C++11 in VS2013.

Related

Public ref class implementing internal interface in C++/CX

I have a Windows Runtime component in which all of my classes need to expose a handle internally:
private interface class IHandleContainer {
IntPtr GetHandle();
}
namespace Foo {
public ref class Bar: IHandleContainer { ... }
public ref class Baz: IHandleContainer {
internal:
virtual IntPtr GetHandle() = IHandleContainer::GetHandle;
}
}
I don't need IHandleContainer to be public, but I do need IHandleContainer to be on the interface list so that each of my internal objects can be safe_cast<IHandleContainer> successfully.
Being outside of a namespace, IHandleContainer should not be emitted to metadata, but should have a COM GUID associated with it and by listing it on the ref class's interface list, CX should be able to wire up the correct response to QueryInterface. Structurally, everything should "just work." But the compiler isn't cooperating:
error C3991: 'Foo::Baz': cannot implement a non-public or nested interface 'IHandleContainer'
Unfortunately this is not possible using C++/CX, and none of the tricks you might try will work.
Interface members can't be internal
There is no such thing as internal inheritance
public WinRT types can't derive from private bases
WinRT types can't derive from non-WinRT types
public WinRT types can't be unsealed unless they derive from something that is unsealed
That last one is recursive, and the only way out of it is to derive from an existing unsealed platform-provided type like DependencyObject, but you really don't want to do that.
You need to use something CloakedIid in WRL, or Kenny Kerr's pure C++ example on MSDN Magazine. Either way you have to define your types in IDL and implement them the "hard" way.

signature of public member contains native type

I am new to visual c++, I have the following code:
ref class Book sealed
{
public:
Book(std::string title,std::string author,int year);
void setTitle(std::string title);
std::string getTitle() const;
int getYear() const;
void setYear(int year);
void setAuthor(std::string author_);
std::string getAuthor() const;
private:
std::string title_;
std::string author_;
int year_;
};
When I am trying to compile it I am getting the following error:
{ctor} signature of public member contains native type. I suppose this is because I am using an the std::string and not the Platform::String, how can I fix that?
Your ref class is not marked public itself, so it appears you are only consuming this class internally (as source) from other C++, and not intending for it to be published to other WinRT consumers.
If this is the case, you can set your constructor as internal instead of public, which will be public within this component and not visible externally. And really if that's your intended usage, then it can just be a regular 'class' instead of a 'ref class'. If you do wish to use it across the WinRT boundary but you don't need the constructor, you can make it a 'public ref class' and have the constructor marked as 'internal'. Kinda depends on your scenario.
If you instead wish to make this class public and have a public constructor which is usable across the WinRT boundary (so that it can be consumed by C#/VB/JS), then you need to use WinRT types (such as Platform::String). Within your class the storage type can still be a std::string (although I recommend using std::wstring, otherwise you need to do wide-to-narrow conversions, as Platform::Strings are wide strings).
To convert between these two types, use Platform::String::Data() to get at the underlying wchar_t* which you can use to construct a std::wstring. And similarly, Platform::String has a constructor which takes a wchar_t* (which you can get from std::wstring::c_str()).
You can't hold native types in a managed reference class.
You can only hold a pointer to an unmanaged object(a pointer is just a number after all, and that's why it's allowed).

Using constants as default parameter values in interfaces: IDE okay but mxmlc fails?

This code seems to compile fine in the IDE, but the command-line compiler (SDK 4.5 mxmlc.exe) reports "Parameter initializer unknown or is not a compile-time constant."
senocular gives a good explanation and a maybe-workaround, but I'm hoping for something more elegent (like a command-line instruction).
package {
public class Constants {
public static const CONSTANT : int = 0;
}
}
package {
public interface IInterface {
function foo( param : int = Constants.CONSTANT ) : void;
}
}
package
{
public class Concrete implements IInterface
{
public function foo(param:int=Constants.CONSTANT):void
{
}
}
}
According to Senocular, it's all about the compilation order. There's no explicit way to set this order.
You could define inline constants using the define compiler option to avoid this problem.
Another way would be to create a library containing the constants. Libraries are included before user classes.
To create a library use the component compiler:
compc -output lib\Constants.swf -source-path src -include-classes Constants
When compiling the application, include that library:
mxmlc -include-libraries lib\Constants.swf -- src\Main.as
Just don't forget to recompile the library when the constants change, or use a build script that takes care of that.
A short comment on the example code:
The interface doesn't need to use that constant, any value will do and have the same effect on implementing classes.
Programming AS3 - Interfaces
A method that implements such a function declaration must have a default parameter value that is a member of the same data type as the value specified in the interface definition, but the actual value does not have to match.

private/public class in namespace problem

This is a question about what defining a class as public or private does.
Right now, I have various classes defined inside of a namespace and I only want some of those classes to be visible/usable to the outside world.
So, for example, if the classes below were the only ones in the program, I would want main.cpp to only be able to see/use the MyPublic class, not the MyPrivate class. I thought that defining the MyPrivate class as private and the MyPublic class as public would accomplish this, but the below code works and main.cpp is able to declare a MyPrivate object.
Is it possible to do this in C++?
MyPrivate.h:
namespace MyNamespace{
// only classes inside of the MyNamespace should be able
// to use this
private ref class MyPrivate{
...
};
}
MyPublic.h:
#include "MyPrivate.h"
namespace MyNamespace {
// anyone can declare this
public ref class MyPublic{
...
private:
MyNamespace::MyPrivate^ p;
...
};
}
Main.cpp:
#include "MyPublic.h"
int main(){
MyNamespace::MyPublic p_yes; // this is fine
MyNamespace::MyPrivate p_no; // don't want this to be possible
return 0;
}
private/public in this situation will affect how classes are visible outside an assembly, if you want to create a class that is "private" in the meaning that it can be used only by some other class, you can use nested clas mechanism, like this:
namespace MyNamespace {
public ref class MyPublic {
private:
ref class MyPrivate {
public:
int x;
};
MyPrivate^ p;
};
}
//Edit:
You can by the way still throw this nested class in public: section and use it like this:
MyNamespace::MyPublic::MyPrivate priv;
The private keyword means something else than you think. I limits visibility of the ref class beyond the assembly. Since your Main() method is in the same assembly, it has no trouble referencing the type name. Note that the C# language's "internal" keyword means the same thing.
I assume that you really intend for these classes to be in a separate assembly someday. As such, using private is certainly good enough. Using nested private classes can make a class inaccessible to code in the same assembly.
You public header shouldn't include private header. Forward declare private class and include header only in MyPublic.cpp. Or that's what I'd say if you used normal C++. Bastardized .Net dialect might change things.
Unfortunately, the access modifiers on a class only affect visibility outside the assembly you're building. C++ doesn't support any sort of access modifiers that apply to namespaces in the way you're describing.
A common idiom for simulating this is to put the "private" code into a detail namespace (e.g. put it in MyNamespace::detail). This is used a lot in e.g. the boost libraries. By convention, code in a detail namespace should only be used by code in the enclosing namespace (so MyNamespace::detail should only be used by code in MyNamespace), although the compiler won't enforce this for you.

Can anybody explain the concept of pluggable adapter to me with good example?

Can anybody explain the concept of pluggable adapter to me with good example?
From what I understood from a quick reading of Google results, a pluggable adapter is an adapter that isn't hard-coded against a specific adaptee. On the surface (the adapter's own interface), it's all the same but it can adapt to different adaptees with different interfaces. I found this thread pretty explanatory:
Basically, it allows you to put in an
adapter when the adaptee (receiver)
protocol is not known at compile time
by using reflection. When you create
the adapter instance, you pass it the
name of the adaptee's method to call,
and also any metadata that's necessary
to translate input types. When the
adapter receives a method call of the
target interface, it uses reflection
to call the corresponding method
specified on the adaptee.
And this:
The main responsibility of the Viewer
is to populate a widget from a domain
model without making any assumptions
about domain itself. JFace viewer uses
the Delegating Objects mechanism in
Pluggable Adapter Pattern to implement
the above requirement.
Think of it as a facehugger from Alien; when it hugs a face, all you see is the slimy back of the facehugger. You can poke it with a stick and try to pry off its arms (the adapter interface). But it basically can hug the face of any human (the adaptee), regardless of the face features. Maybe I'm pushing it a bit, but, hey, I love Alien.
You can read this article about adapter/pluggable pattern:
Table of content in this article:
* 1 Design Patterns
* 2 Intent of Adapter
* 3 Motivation
* 4 Structure
* 5 Applicability
* 6 Consequences
* 7 Implementation
o 7.1 Known Uses and Sample Code
o 7.2 Related Patterns
* 8 Conclusions
* 9 Appendix
o 9.1 References
o 9.2 Glossary
Quote:
Smalltalk introduced the concept of a
"pluggable adapter" to describe
classes with built-in interface
adaptation. This interesting concept
allows for classes to be introduced
into existing systems that might
expect different interfaces to the
class. This technique can help promote
class reuse across modules and even
projects.
Here is a small example:
We have two classes - Foo & Boo that outputs some string to console. Adapter class can adapt methods from both classes to provide interface (SaySomething) required by client. Note that there is no dependency on interface name - we can easily adapt both SayHey and Bark methods.
class Foo
{
public static void SayHey() { Console.WriteLine("Hey!"); }
}
class Boo
{
public static void Bark() { Console.WriteLine("Woof!"); }
}
class Adapter
{
public Action SaySomething { get; private set;} // "pluggable" adapter
public Adapter(Action saySomethingAction)
{
SaySomething = saySomethingAction;
}
}
class Program
{
static void Main(string[] args)
{
(new Adapter(Foo.SayHey)).SaySomething();
(new Adapter(Boo.Bark)).SaySomething();
}
}
A distinguish Feature of the Pluggable Adapter is that the method called by the client and the method existing in the interface can be different.
interface Ilegacy
{
float calculate(int a, int b);
}
class Legacy : Ilegacy
{
public float calculate(int a, int b)
{
return a * b;
}
}
class Adapter
{
public Func<int, int, float> legacyCalculator;
public Adapter()
{
this.legacyCalculator = new Legacy().calculate;
}
}
class Client
{
static void Main()
{
float result = new Adapter().legacyCalculator(5, 6);
}
}
This can normally acheived with the use of delegate,Func or Action in C#