我可以分配模板类型 say T 一个类型,取决于另一个模板类型 say U 函数中的类似内容。
typename <class T, class U>
func(U var)
{
...
if(U == int) //this can be replaced with std::is_same<U, int>
{
T = flaot; //instead int/float i have my own data types
}
...
}
这可能吗..如果是的话是怎么做到的
最佳答案
不确定这是不是你想要的,但你可以试试这个:
template <typename T>
class Selector; // implement this one as well, if you want to have a default...
template <> class Selector<int> { public: using Type = ClassX; };
template <> class Selector<double> { public: using Type = ClassY; };
template<typename U>
void func(U var)
{
using T = typename Selector<U>::Type;
};
变体:
template<typename U, typename T = typename Selector<U>::Type>
void func(U var) { }
如果需要,这将允许替换所选类型:
func(12); // uses default: ClassX
func<int, ClassZ>(10); // replace ClassX with ClassZ
关于c++ - 根据另一个模板类型决定一个模板类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696443/