这可以与带有模板元编程的字符数组一起使用吗? [英] Is this possible to work with character arrays with Template Metaprogramming?
本文介绍了这可以与带有模板元编程的字符数组一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一系列模板,以基于多达32种数据类型填充32个字符串.是否可以在编译时进行计算?
我的假设是不,但想验证以防万一我错了.
生成具有3种数据类型的注册字符串的代码示例
temp [0] = Char_Type < T1 < T2 > ();
temp [2] = Char_Type < T3 > ();
return temp;
解决方案
也许这是一些值得深思的事情. 内联 char char_type(){返回 ' -'; } 模板<> 内联 char char_type< char>(){>返回 ' c'; } 模板<> 内联 char char_type< int>(){返回 ' d'; } 模板< typename T1, typename T2> 类 MyClass { 公共: 静态 字符 temp []; // 将在编译时初始化 }; 模板< typename T1, typename T2> char MyClass< T1,T2> :: temp [] = {char_type< T1>(),char_type< T2>(), int main() { cout<< MyClass< int,char> :: temp<<恩德尔 cin.get(); 返回 0 ; }
将其变成一个有效的示例,并删除了模板参数上的约束.
我不完全确定您要实现的目标,但是由于每个是唯一类型,如果它们是相同基类(或该基类的实例)的子类,则只能将它们分配给相同的集合(在您的情况下为 temp[]
数组). >
class some_base { }; 模板< T类> class Char_Type: public some_base { 公共: T 值; Char_Type() { }; Char_Type( const T& v) { 值 = v; }; }; int main( int argc, char * argv []) { some_base * a = 新 some_base [ 3 ]; a [ 0 ] = Char_Type< char>(' c '); a [ 1 ] = Char_Type< int>( 123 ); a [ 2 ] = Char_Type< int>( 123 . 23 ); 删除 [] a; 返回 0 ; }
但是我认为这样的设置会取消您尝试执行的操作.
I''ve written a series of templates to fill in a 32 character string based on up to 32 data types. Is it possible to compute this at compile time?
My assumption is no, but wanted to verify in case I was wrong.
Example of code to generate registration string with 3 data types
temp[0]=Char_Type<T1>();
temp[1]=Char_Type<T2>();
temp[2]=Char_Type<T3>();
return temp;
解决方案
Maybe this would be some food for thoughttemplate<typename T> inline char char_type() { return '-'; } template<> inline char char_type<char>() { return 'c'; } template<> inline char char_type<int>() { return 'd'; } template <typename T1, typename T2> class MyClass { public: static char temp[]; // Will be init'ed at compile time }; template <typename T1, typename T2> char MyClass<T1, T2>::temp[] = { char_type<T1>(), char_type<T2>(), 0 }; int main() { cout << MyClass<int, char>::temp << endl; cin.get(); return 0; }
Edit: Turned it into a working sample, and removed the constraints on the template parameters.
I''m not entirely sure what you''re trying to achieve, but since eachChar_Type<T>
is a unique type, they can only be assigned to the same collection (in your case thetemp[]
array), if they''re subclasses of the same base class (or an instance of that base class).
class some_base { }; template<class T> class Char_Type : public some_base { public: T value; Char_Type() { }; Char_Type(const T& v) { value = v; }; }; int main(int argc, char* argv[]) { some_base* a = new some_base[3]; a[0] = Char_Type<char>('c'); a[1] = Char_Type<int>(123); a[2] = Char_Type<int>(123.23); delete[] a; return 0; }
But I think such a setup would cancel what you''re trying to do.
这篇关于这可以与带有模板元编程的字符数组一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文