Nya*_*hes 5 c++ refactoring templates dynamic c++11
这是我想要实现的运行示例:
#include <iostream>
#include <string>
#include <typeinfo>
template <class T>
struct print
{
static void function( T thing)
{
std::cout << thing << std::endl;
}
};
template <class T>
struct printMore
{
static void function( T thing )
{
std::cout << thing << " and more" << std::endl;
}
};
struct dynamicBase
{
const char* m_value;
size_t getType()
{
switch( *m_value )
{
case '0': //the string is going to be a small script, the type returned is known during execution but not at compile time
return typeid( int ).hash_code();
case '1':
return typeid( float ).hash_code();
}
return typeid( const char* ).hash_code();
}
template<class T>
T* tryGetValue()
{
if( getType() == typeid( T ).hash_code() )
return (T*) ( &( m_value[1] ) ); //dumb example, actually I'll evaluate the string as script and return a value based on that
else
return nullptr;
}
void applyPrint( )
{
if( int* t = tryGetValue<int>() )
print<int>::function( *t ); //I can cout an int so this line compile
else if( float* t = tryGetValue<float>() )
print<float>::function( *t ); //I can cout a float so this one too
else
print<const char*>::function( *tryGetValue<const char*>() ); //same
}
void applyPrintMore()
{
if( int* t = tryGetValue<int>() )
printMore<int>::function( *t );
else if( float* t = tryGetValue<float>() )
printMore<float>::function( *t );
else
printMore<const char*>::function( *tryGetValue<const char*>() ); //same
}
//.... applyprintPretty, applyprintInRed, applyprintInBlue, .....
};
int main()
{
dynamicBase d;
d.m_value = "0a\0\0\0";
d.applyPrint(); //97 == ascii value of 'a'
__asm {nop}; //for breakpoint purpose
}
Run Code Online (Sandbox Code Playgroud)
一开始我虽然可以使用这样的模板:
template<class myFunctionClass>
void applyPrint( )
{
if( int* t = tryGetValue<int>() )
myFunctionClass<int>::function( *t );
else if( float* t = tryGetValue<float>() )
myFunctionClass<float>::function( *t );
else
myFunctionClass<const char*>::function( *tryGetValue<const char*>() );
}
Run Code Online (Sandbox Code Playgroud)
然后意识到我的错误(在您为模板类型提供模板参数之前,模板类型不是类型)。但是有没有办法重构此代码,所以我没有15个applyStuff函数?(我做错了,不是吗?)
您正在寻找模板模板参数:
template<template <typename> class myFunctionClass>
void applyPrint( )
{
if( int* t = tryGetValue<int>() )
myFunctionClass<int>::function( *t );
else if( float* t = tryGetValue<float>() )
myFunctionClass<float>::function( *t );
else
myFunctionClass<const char*>::function( *tryGetValue<const char*>() );
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到参考:“cppreference.com - Template 模板参数”。