Hi,
Are some of you using the template keyword and if yes, when/for what? I mean I have never really encountered the need of using it for game development…
Yes there are many use case for that, for example a prefab made just to serve the purpose of a template. Like you have a consumable item prefab as a template, extra configuration on top will need to be made during runtime such as changing certain label strings.
thanks for the quick reply! But can you give an example of a “consumable item prefab as a template” because I do not know if I get what you mean by that.
This pice of code creates autorelease cocos object with arguments forwarding to constructor. That allows me to not write ‘create’ static method in each coocs2d child class
#pragma once
#ifndef COCOS_HELPER_HPP
#define COCOS_HELPER_HPP
#include <type_traits>
namespace app { namespace util {
/*
Create autorelease cocos object
@note T must be derived from cocos2d::Ref
@param args [optional] arguments that forwards to T constructor
@return autorelease object
*/
template<typename T, typename... Args>
inline T* make_autorelease( Args&&... args )noexcept {
static_assert( std::is_base_of<cocos2d::Ref, T>::value,
"T must be derived from cocos2d::Ref" );
auto pRet = new( std::nothrow ) T{ std::forward<Args>( args )... };
if ( pRet && pRet->init( ) ) {
pRet->autorelease( );
return pRet;
} else {
delete pRet;
pRet = nullptr;
return nullptr;
}
}
} }
#endif
Thank you. Fantastic with an example
You could also use templates for container class that could have many type parameters on it
class Vector {
private:
std::array<T, size> data;
public:
Vector() : Vector<T, size>(T(0)) {}
Vector(T value) {
for (int i = 0; i < size; ++i) {
data[i] = value;
}
}
Vector(std::array<T, size> data) {
this->data = data;
}
template<typename scalar>
Vector<T, size>& multiply(scalar factor) {
for (int i = 0; i < size; ++i) {
data[i] *= factor;
}
return *this;
}
}
with this you could easily use a vector of int or vector of floats, etc