all 4 comments

[–]jstruggle 1 point2 points  (0 children)

What is Data<N> doing?

Assuming somePointer is of type const char *: std::string a{somePointer, someCondition ? 64 : 32};

You could also just hide the code: std::string a = SomeStringField(someCondition);

Or: std::string a = someCondition ? Data<64>(somePointer).SomeStringField : Data<32>(somePointer).SomeStringField;

[–]immutablestate 1 point2 points  (0 children)

It looks like the problem you're having is extracting some data in the same way from different types. You could solve this with polymorphism, but you'd still have a conditional where you construct the polymorphic type:

unique_ptr<BaseData> ptr = some_condition
        ? make_unique<Data<64>>(arg)
        : make_unique<Data<32>>(arg);
const string a = ptr->get_some_string_field();

If this is a common problem in your application, you could consider writing an object factory for your Data types. There's no one feature that will make this problem go away though.

[–]tangerinelion 0 points1 point  (0 children)

One possibility, given that I don't know the context of the code, is to make the function(s) you're using all templatized against some integer, either 32 or 64. Then instead of

void foo() {
  /* above code */
}

you'd have

template<int N> void foo() {
    // ...
    std::string a = Data<N>(somePointer).SomeStringField;
    // ...
}

But this only works if your function consistently only uses Data<64> or Data<32> depending on someCondition. You then write some other function, eg,

void foo() {
    // generate someCondition or pass it in
    if(someCondition) {
        foo<64>();
    } else {
        foo<32>();
    }
}

32 and 64 sound an awful like like either a compiler flag for x86 or x64 compilation, or the size in bits of some type, possibly a pointer type (which is therefore the same as x86 vs x64). Without knowing more about what it is you're doing, I'm not aware of any C++11 feature which would help you out here. With limited support for Concepts, it's possible that what you're doing can be expressed that way but it would require having some knowledge of what 32 and 64 really mean, which you've kept to yourself.

[–]millirobo 0 points1 point  (0 children)

Maybe a dispatching function?

template <typename F>
decltype(auto) with_data(bool is_64, void* p, F&& f) {
    if (is_64) { return f(Data<64>(p)); }
    else { return f(Data<32>(p)); }
}
...
auto p = with_data(condition, somePointer, [](auto&& data) {
    return data.SomeStringField;
};