I am new to template programming. I have a question like this
A.process(B)
where A is a template parameter.
Is it fine for me to set B as a template parameter as well? By that I would be able to let different type A objects to process different type of objects B. B normally would not be used polymorphically in run time.
Thanks.
If I understand your requirement, then yes - you can do something like:
template <typename A, typename B>
void fn(A& a, B& b)
{
...other code...
a.process(b);
...other code...
}
Well, since we're all speculating on the meaning of the question, I'll offer what I think is in mind here. In the same way that one can create a template like -
template<typename T, std::size_t size = 50> struct fixed_array {
private:
T a[size];
};
...with "size" being an instance of an existing type, and not the name of a type, I think the questioner wants to know if one can do something like the following -
struct A_type {
... // whatever constitutes this class plus overloaded methods like ...
void process(int B) {
std::cout << "int overload: " << B << std::endl;
}
void process(const char* B) {
std::cout << "string overload: " << B << std::endl;
}
} A; // an actual instance of A_type
template<A_type A, int B> void foo() {
A.process(B); // will call the int overload
}
main() {
foo<A, 3>(); // produces the output "int overload: 3"
}
The answer is "no". At least, not as formulated above. There are restrictions on non-type template parameters that are well-summarized here: template parameters. The type of such a parameter has to conform to LiteralType, which includes references. So by tweaking the function definition as follows -
template<A_type& A, int B> void foo() {
A.process(B); // will call the int overload
}
Now we're good-to-go, and it satisfies the questioner's requirement to produce a template (class or function) in which A and B, both of which are clearly instances and not types, are both parameterized at compile time, such that A.process(B) can be understood and compiled. By C++20, there are a set of rules that allow the original formulation of foo if A_type obeys a number of conventions, but that's all covered in the above link. NOTE: while LiteralType entities can include references, the object of those references must be statically defined, either in the global declaration area or declared with the keyword static. The compiler must know the value at compile time, and it must be impossible to change at run-time. So for example the following -
template<A_type& A, const char* B> void bar() {
A.process(B);
}
this main definition will not compile -
main() {
bar<A, "hello">();
}
but the following will -
const char* h_string = "hello";
template<A_type& A, const char*& B> void bar() { // note the switch to reference
A.process(B);
}
main() {
bar<A, h_string>(); // will produce output "string overload: hello"
}
as will -
main() {
static const char* h_string = "hello";
bar<A, h_string>();
}
For reasons I can't quite work out, even using double in stead of int didn't work in the version of clang I tried this on, so it may not be as flexible a trick as the questioner would like. That being said, there are without doubt many other approaches to solving the questioner's higher level problem.
Related
I'm trying to declare a class "Lambdas" that would provide lambdas (and their type information) to another class "Test". Lambdas also is holding the "this" reference to concrete Test instance for access of Test public members, inside the lambdas.
I do it to define the lambdas once and then to deduce types anywhere else through decltype()
But I get error: Member access to incomplete type:
template <typename T>
struct LambdasInstances {
T * self;
explicit LambdasInstances(T * p) : self(p) {} // CAPTURE Test "this"
auto genLambda1() {
return [=](int x){
self->testVar; // ERROR: Member access to incomplete type
};
}
};
class Test3 {
public:
LambdasInstances<Test3> instances;
int testVar;
Test3() : instances(this) {}
decltype(instances.genLambda1()) varLambda = instances.genLambda1();
void useLambda() { varLambda(123); }
};
BUT IF I would make genLambda() externally defined, then I would run to another problem - ERROR: genLambda() with deduced type cannot be used before its defined!:
template <typename T>
struct LambdasInstances {
T * self;
explicit LambdasInstances(T * p) : self(p) {}
auto genLambda1(); // would be defined after Test3 declaration
};
class Test3 {
public:
int testVar;
LambdasInstances<Test3> instances;
Test3() : instances(this) {}
decltype(instances.genLambda1()) varLambda = instances.genLambda1();
};
// IF WE DEFINE AFTER :: ^ genLambda() with deduced type cannot be used before its defined!
template< typename T>
auto LambdasInstances<T>::genLambda1() {
return [=](int x){
self->testVar;
};
}
The compiler might require the definition of the whole type available to be able to know the offset of the members (e.g. in the expression self->testVar, the compiler has to know the offset of testVar), but it might not be able to know the offset of a particular member until it will get the whole definition, because the compiler must know the alignment of your structure/class (I would even guess that some not straight forward logic might be involved when computing the padding between members) that comes after the knowledge of all members, see this, that is totally compiler and platform specific.
So back to your problem. You tell the compiler to define Test3 with genLambda1 as a member, that is a lambda that has to know the offset of member testVar. Seems easy, right? But the offset of testVar depends on the definition of the whole Test3 (see the paragraph above) - here we are in the loop.
You would say: "Hey stupid compiler, I give only a pointer to the lambda, not a copy by value where you have to know the whole size of the `Test3, why would you stop me from doing that?". Quite a legit question because theoretically compiler can resolve offset later, but seems like the compilers are not smart enough. And the standard says:
The lambda-expression’s compound-statement yields the function-body (8.4) of the function call operator ...
That basically says that the lambda body is the function body, but in the function body you cannot have incomplete types right? Lambdas are relatively new to C++ and not all corner cases are elaborated, so let's hope that in some future this will be resolved, of course the compilers will be more complicated as well as the standard.
For you problem I see the following resolution:
template <typename T>
struct LambdasInstances {
explicit LambdasInstances(T* p) : _lambda([=](int x) { return p->testVar; }) {}
auto genLambda1() { return _lambda; }
private:
std::function<void(int)> _lambda;
};
class Test3 {
public:
int testVar;
LambdasInstances<Test3> instances;
Test3() : instances(this) {}
decltype(instances.genLambda1()) varLambda = instances.genLambda1();
};
int main() {
Test3 test3;
Test3* test3_ptr;
LambdasInstances<Test3> instances(&test3);
auto lambda = [=](int x) { return test3_ptr->testVar; };
std::function<void(int)> functor = lambda;
cerr << sizeof(Test3) << endl;
cerr << sizeof(LambdasInstances<Test3>) << endl;
cerr << sizeof(lambda) << endl;
cerr << sizeof(functor) << endl;
return 0;
}
The difference is that std::function gives you a level of abstraction that protects the type LambdasInstances::genLambda1 from the definition of Test3. Unfortunately, as you will see from the main output the function takes more memory than the lambda. If this does not satisfy your needs I recommend to revise the design and may be you will find something in the old good techniques before the era of lambdas.
Sorry for the uninformative title, I don't really know what to call what I am asking.
I want to achieve the following: Having a container of a base class type with instances of derived types, accessing the containers and calling a function overload dependent on the type of the derived object accessed. In a question earlier I asked here I learned that the static design I had in mind so far, does not work. The way I tried is this:
struct Int2TypeBase{
};
template <int v>
struct Int2Type : public Int2TypeBase
{
enum
{
value = v
};
};
void f(const Int2Type<0>&){
std::cout << "f(const Int2Type<0>&)" << "\n";
}
void f(const Int2Type<1>&){
std::cout << "f(const Int2Type<1>&)" << "\n";
}
int main(){
using namespace std;
std::vector<std::reference_wrapper<Int2TypeBase>> v;
Int2Type<0> i2t_1;
v.emplace_back(i2t_1);
Int2Type<1> i2t_2;
v.emplace_back(i2t_2);
auto x0 = v[0];
auto x1 = v[1];
f(x0.get()); // After my imagination this would have called void f(const Int2Type<0>&)
f(x1.get()); // After my imagination this would have called void f(const Int2Type<1>&)
}
Ok, so I want the correct overload of f to be selected, this however does not compile as at compile time it is unknown which type x0 and x1 actually have. But is there some alternate design that can realize this behavior?
Overloading is a static mechanism based on static types.
If you want to change behaviour dynamically based on the dynamic type of an object, C++ provides another built-in language feature for that: Virtual functions. Use them like this:
struct Int2TypeBase
{
virtual void do_f() = 0;
};
template <int v> struct Int2Type : Int2TypeBase
{
void do_f() override
{
// specific behaviour for Int2Type<v> goes here
}
/* ... */
};
void f(Int2TypeBase & x) { x.do_f(); }
Now you can call f on any base subobject and the correct behaviour is selected at runtime. In particular, f(x0.get()) and f(x1.get()) now select and dispatch to Int2Type<0>::do_f and Int2Type<1>::do_f at runtime, respectively.
Imagine you have a number of overloaded methods that (before C++11) looked like this:
class MyClass {
public:
void f(const MyBigType& a, int id);
void f(const MyBigType& a, string name);
void f(const MyBigType& a, int b, int c, int d);
// ...
};
This function makes a copy of a (MyBigType), so I want to add an optimization by providing a version of f that moves a instead of copying it.
My problem is that now the number of f overloads will duplicate:
class MyClass {
public:
void f(const MyBigType& a, int id);
void f(const MyBigType& a, string name);
void f(const MyBigType& a, int b, int c, int d);
// ...
void f(MyBigType&& a, int id);
void f(MyBigType&& a, string name);
void f(MyBigType&& a, int b, int c, int d);
// ...
};
If I had more parameters that could be moved, it would be unpractical to provide all the overloads.
Has anyone dealt with this issue? Is there a good solution/pattern to solve this problem?
Thanks!
Herb Sutter talks about something similar in a cppcon talk
This can be done but probably shouldn't. You can get the effect out using universal references and templates, but you want to constrain the type to MyBigType and things that are implicitly convertible to MyBigType. With some tmp tricks, you can do this:
class MyClass {
public:
template <typename T>
typename std::enable_if<std::is_convertible<T, MyBigType>::value, void>::type
f(T&& a, int id);
};
The only template parameter will match against the actual type of the parameter, the enable_if return type disallows incompatible types. I'll take it apart piece by piece
std::is_convertible<T, MyBigType>::value
This compile time expression will evaluate to true if T can be converted implicitly to a MyBigType. For example, if MyBigType were a std::string and T were a char* the expression would be true, but if T were an int it would be false.
typename std::enable_if<..., void>::type // where the ... is the above
this expression will result in void in the case that the is_convertible expression is true. When it's false, the expression will be malformed, so the template will be thrown out.
Inside the body of the function you'll need to use perfect forwarding, if you are planning on copy assigning or move assigning, the body would be something like
{
this->a_ = std::forward<T>(a);
}
Here's a coliru live example with a using MyBigType = std::string. As Herb says, this function can't be virtual and must be implemented in the header. The error messages you get from calling with a wrong type will be pretty rough compared to the non-templated overloads.
Thanks to Barry's comment for this suggestion, to reduce repetition, it's probably a good idea to create a template alias for the SFINAE mechanism. If you declare in your class
template <typename T>
using EnableIfIsMyBigType = typename std::enable_if<std::is_convertible<T, MyBigType>::value, void>::type;
then you could reduce the declarations to
template <typename T>
EnableIfIsMyBigType<T>
f(T&& a, int id);
However, this assumes all of your overloads have a void return type. If the return type differs you could use a two-argument alias instead
template <typename T, typename R>
using EnableIfIsMyBigType = typename std::enable_if<std::is_convertible<T, MyBigType>::value,R>::type;
Then declare with the return type specified
template <typename T>
EnableIfIsMyBigType<T, void> // void is the return type
f(T&& a, int id);
The slightly slower option is to take the argument by value. If you do
class MyClass {
public:
void f(MyBigType a, int id) {
this->a_ = std::move(a); // move assignment
}
};
In the case where f is passed an lvalue, it will copy construct a from its argument, then move assign it into this->a_. In the case that f is passed an rvalue, it will move construct a from the argument and then move assign. A live example of this behavior is here. Note that I use -fno-elide-constructors, without that flag, the rvalue cases elides the move construction and only the move assignment takes place.
If the object is expensive to move (std::array for example) this approach will be noticeably slower than the super-optimized first version. Also, consider watching this part of Herb's talk that Chris Drew links to in the comments to understand when it could be slower than using references. If you have a copy of Effective Modern C++ by Scott Meyers, he discusses the ups and downs in item 41.
You may do something like the following.
class MyClass {
public:
void f(MyBigType a, int id) { this->a = std::move(a); /*...*/ }
void f(MyBigType a, string name);
void f(MyBigType a, int b, int c, int d);
// ...
};
You just have an extra move (which may be optimized).
My first thought is that you should change the parameters to pass by value. This covers the existing need to copy, except the copy happens at the call point rather than explicitly in the function. It also allows the parameters to be created by move construction in a move-able context (either unnamed temporaries or by using std::move).
Why you would do that
These extra overloads only make sense, if modifying the function paramers in the implementation of the function really gives you a signigicant performance gain (or some kind of guarantee). This is hardly ever the case except for the case of constructors or assignment operators. Therefore, I would advise you to rethink, whether putting these overloads there is really necessary.
If the implementations are almost identical...
From my experience this modification is simply passing the parameter to another function wrapped in std::move() and the rest of the function is identical to the const & version. In that case you might turn your function into a template of this kind:
template <typename T> void f(T && a, int id);
Then in the function implementation you just replace the std::move(a) operation with std::forward<T>(a) and it should work. You can constrain the parameter type T with std::enable_if, if you like.
In the const ref case: Don't create a temporary, just to to modify it
If in the case of constant references you create a copy of your parameter and then continue the same way the move version works, then you may as well just pass the parameter by value and use the same implementation you used for the move version.
void f( MyBigData a, int id );
This will usually give you the same performance in both cases and you only need one overload and implementation. Lots of plusses!
Significantly different implementations
In case the two implementations differ significantly, there is no generic solution as far as I know. And I believe there can be none. This is also the only case, where doing this really makes sense, if profiling the performance shows you adequate improvements.
You might introduce a mutable object:
#include <memory>
#include <type_traits>
// Mutable
// =======
template <typename T>
class Mutable
{
public:
Mutable(const T& value) : m_ptr(new(m_storage) T(value)) {}
Mutable(T& value) : m_ptr(&value) {}
Mutable(T&& value) : m_ptr(new(m_storage) T(std::move(value))) {}
~Mutable() {
auto storage = reinterpret_cast<T*>(m_storage);
if(m_ptr == storage)
m_ptr->~T();
}
Mutable(const Mutable&) = delete;
Mutable& operator = (const Mutable&) = delete;
const T* operator -> () const { return m_ptr; }
T* operator -> () { return m_ptr; }
const T& operator * () const { return *m_ptr; }
T& operator * () { return *m_ptr; }
private:
T* m_ptr;
char m_storage[sizeof(T)];
};
// Usage
// =====
#include <iostream>
struct X
{
int value = 0;
X() { std::cout << "default\n"; }
X(const X&) { std::cout << "copy\n"; }
X(X&&) { std::cout << "move\n"; }
X& operator = (const X&) { std::cout << "assign copy\n"; return *this; }
X& operator = (X&&) { std::cout << "assign move\n"; return *this; }
~X() { std::cout << "destruct " << value << "\n"; }
};
X make_x() { return X(); }
void fn(Mutable<X>&& x) {
x->value = 1;
}
int main()
{
const X x0;
std::cout << "0:\n";
fn(x0);
std::cout << "1:\n";
X x1;
fn(x1);
std::cout << "2:\n";
fn(make_x());
std::cout << "End\n";
}
This is the critical part of the question:
This function makes a copy of a (MyBigType),
Unfortunately, it is a little ambiguous. We would like to know what is the ultimate target of the data in the parameter. Is it:
1) to be assigned to an object that existing before f was called?
2) or instead, stored in a local variable:
i.e:
void f(??? a, int id) {
this->x = ??? a ???;
...
}
or
void f(??? a, int id) {
MyBigType a_copy = ??? a ???;
...
}
Sometimes, the first version (the assignment) can be done without any copies or moves. If this->x is already long string, and if a is short, then it can efficiently reuse the existing capacity. No copy-construction, and no moves. In short, sometimes assignment can be faster because we can skip the copy contruction.
Anyway, here goes:
template<typename T>
void f(T&& a, int id) {
this->x = std::forward<T>(a); // is assigning
MyBigType local = std::forward<T>(a); // if move/copy constructing
}
If the move version will provide any optimization then the implementation of the move overloaded function and the copy one must be really different. I don't see a way to get around this without providing implementations for both.
Suppose I have following template class:
template<unsigned char I, unsigned char F>
class FOO
{
....
}
In the main function, I have many such variables, with different (I, F), like following,
int main()
{
.....
FOO<4, 2> a;
FOO<6, 3> b;
......
}
I want to retain the value of I or F for the defined variables in my main function. Of course, I can define a public/private members for FOO and save the value of (I, F) inside the FOO's constructor, like
template<I,F>
FOO<I,F>::FOO(){
i = I;
f = F;
}
Disadvantage of this method is obvious: It enlarge the size of the FOO. IMO, (I, F) of any variable can be determined at compiling time, so there should be a way to do this without creating local variable.
The usual way (like std::array in C++11) is to do the following:
constexpr unsigned char i() const { return I; }
constexpr unsigned char f() const { return F; }
If your compiler doesn't support constexpr, remove it.
Within your class definition, you can simply refer to the parameters literally (just like any other template parameters!).
But suppose you have this:
typedef Foo<10, 20> MyFoo;
MyFoo x; // what is I, what is K?
The customary thing is to reflect the template parameters inside the class definition:
template <int A, typename T> struct Foo
{
static int const a_value = A;
typedef T type;
// ...
};
Now you can say: MyFoo::type x; return MyFoo::a_value; etc. Note that integral static class constants don't usually need a definition unless you do something like take their address, so in most cases this won't have any cost in the compiled code -- the compiler simply substitutes the value whenever it sees the name of the constant.
you can simply use the template parameters, like this:
#include <iostream>
using namespace std;
template<unsigned char I, unsigned char F>
class FOO
{
public:
void bar() {
cout << "I is: "<<I<<endl;
}
char getI() {
return I;
}
};
using namespace std;
int main(){
FOO<4,2> a;
a.bar();
cout << "getI:"<<a.getI()<<endl;
}
you don't need a copy, as in your example (i = I)
BTW: fully capitalized names like FOO are usually by convention reserved for preprocessor Macros.
What is compile-time polymorphism and why does it only apply to functions?
Way back when, "compile time polymorphism" meant function overloading. It applies only to functions because they're all you can overload.
In current C++, templates change that. Neil Butterworth has already given one example. Another uses template specialization. For example:
#include <iostream>
#include <string>
template <class T>
struct my_template {
T foo;
my_template() : foo(T()) {}
};
template <>
struct my_template<int> {
enum { foo = 42 };
};
int main() {
my_template<int> x;
my_template<long> y;
my_template<std::string> z;
std::cout << x.foo << "\n";
std::cout << y.foo << "\n";
std::cout << "\"" << z.foo << "\"";
return 0;
}
This should yield 42, 0, and "" (an empty string) -- we're getting a struct that acts differently for each type.
Here we have "compile time polymorphism" of classes instead of functions. I suppose if you wanted to argue the point, you could claim that this is at least partially the result of the constructor (a function) in at least one case, but the specialized version of my_template doesn't even have a constructor.
Edit: As to why this is polymorphism. I put "compile time polymorphism" in quotes for a reason -- it's somewhat different from normal polymorphism. Nonetheless, we're getting an effect similar to what we'd expect from overloading functions:
int value(int x) { return 0; }
long value(long x) { return 42; }
std::cout << value(1);
std::cout << value(1L);
Function overloading and specialization are giving similar effects. I agree that it's open to some question whether "polymorphism" applies to either, but I think it applies about equally well to one as the other.
With compile time polymorphism one usually means the fact that you can have a several functions with the same name and the compiler will choose at compile time which one to used depending on the arguments:
void foo(int x);
void foo(float y);
//Somewhere else
int x = 3;
foo(x); //Will call first function
float y = 2;
foo(y); //Will call second function
The function foo is said to be overloaded. Various types of template instantiation could also be called compile time polymorphism.
Compile time polymorphism is a term that refers to C++ template programming. For example, at compile time you determine the actual type of a std::vector by what it contains:
std::vector <int> vi;
std::vector <std::string> vs;
I'm not sure why you think it it is limited to functions.
The thing which only applies to functions is template parameter deduction. If I have a function template:
template <typename T>
void foo(T &t);
Then I can do int a = 0; foo(a);, and this will be equivalent to int a = 0; foo<int>(a);. The compiler works out that I mean foo<int>. At least, it works out that it should use foo<int> - if that's not what I meant then bad luck to me, and I could have written foo<unsigned int>(a); or whatever.
However, if I have a class template:
template <typename T>
struct Foo {
T &t;
Foo(T &t) : t(t) {}
T &getT() { return t; }
};
Then I can't do int a = 0; Foo(a).getT();. I have to specify Foo<int>(a). The compiler isn't allowed to work out that I mean Foo<int>.
So you might say that class templates are "less polymorphic" than function templates. Polymorphism usually means that you don't have to write code to make the type of your object explicit. Function templates allow that (in this particular case), and class templates don't.
As for why this is the case - the standard says so, I don't know why. The usual suspects are (a) it's too difficult to implement, (b) it's not useful, in the opinion of the standard committee, or (c) it creates some contradiction or ambiguity somewhere else in the language.
But you can still do other kinds of polymorphism with classes:
template <typename T>
struct Foo {
T &t;
Foo(T &t): t(t) {}
void handleMany(int *ra, size_t s) {
for (size_t i = 0; i < s; ++i) {
t.handleOne(ra[i]);
}
}
};
This is usually also called compile-time polymorphism, because as far as the author of the template is concerned, t.handleOne could be anything, and what it is will be resolved when necessary, "later" in the compilation when Foo is instantiated.
Compile time polymorphism applies to functions and operator overloads.
Read this http://cpp-tutorial.cpp4u.com/OOP_polymorphism.html