gpt4 book ai didi

c++ - 使用非专用模板化类型作为模板参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:18:51 26 4
gpt4 key购买 nike

<分区>

这是我想要实现的运行示例:

#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
}

起初我以为我可以使用这样的模板:

    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*>() );
}

然后意识到我的错误(模板类型不是类型,除非你给它们模板参数)。但是有没有办法重构这段代码,这样我就没有 15 个 applyStuff 函数了? (我做错了,不是吗?)

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com