基于模板变量类型执行不同的方法 [英] Perform different methods based on template variable type
问题描述
有一种方法可以确定传递给模板的变量类型,并根据是否 int
或 std :: string
etc ...?
例如
template< class T>
struct Jam
{
Jam(T * var)
{
if(typeid(var)== typeid(std :: string *)
* var =Hello!;
else if(typeid(var)== typeid(int *)
* var = 25;
}
};
当我尝试使用该代码时,我得到一个错误从const char *我怀疑这是因为编译器扩展模板为单独的函数,当我指定一个新的实例结构 throw Jam< std :: string>(& ; setme); c>它检测到 var * = 25
语句并拒绝编译。
解决方案使用常规函数重载:
/ p>
template< class T>
struct Jam
{
Jam(std :: string * var)
{
* var =Hello!;
}
Jam(int * var)
{
* var = 25;
}
};
,除非您想专门处理类型 T
用于实例化 Jam
。在这种情况下,您可以执行以下操作:
模板<
struct Jam< std :: string>
{
Jam(std :: string * var)
{
* var =Hello!
}
};
模板<>
struct Jam< int>
{
Jam(int * var)
{
* var = 25;
}
};
template< typename T>
struct Jam
{
Jam(T * var)
{
//每隔一种类型
}
}
Is there a way to determine the type of variable passed to a template and call a function based on if it's an int
or std::string
etc...?
For example
template <class T>
struct Jam
{
Jam(T *var)
{
if (typeid(var) == typeid(std::string*)
*var = "Hello!";
else if (typeid(var) == typeid(int*)
*var = 25;
}
};
When I try to use that code, i get an error invalid conversion from const char* to int
. I suspect this is because the compiler "expands" the template into separate functions and when I specified a new instance of the structure throw Jam<std::string>(&setme);
it detected the var* = 25
statement and refused to compile.
Is there a proper way to do this? Maybe with macro guards? Thanks.
解决方案 Use regular function overloading instead:
template <class T>
struct Jam
{
Jam(std::string* var)
{
*var = "Hello!";
}
Jam(int* var)
{
*var = 25;
}
};
unless you want to specialize on the type T
used to instantiate Jam
. In that case you would do:
template<>
struct Jam<std::string>
{
Jam(std::string* var)
{
*var = "Hello!";
}
};
template<>
struct Jam<int>
{
Jam(int* var)
{
*var = 25;
}
};
template<typename T>
struct Jam
{
Jam(T* var)
{
// every other type
}
};
这篇关于基于模板变量类型执行不同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!