当模板模板强制特定的重载 [英] Force a specific overload when template template
本文介绍了当模板模板强制特定的重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下代码:
#include <iostream>
#include <vector>
#include <type_traits>
// Version A
template<typename T>
void f(const T& x)
{
std::cout<<"Version A"<<std::endl;
}
// Version B
template<template<typename> class T, typename T1>
void f(const T<T1>& x)
{
std::cout<<"Version B"<<std::endl;
}
// Main
int main(int argc, char* argv[])
{
f(double());
f(std::vector<double>()); // <- How to force the use of version B ?
return 0;
}
默认情况下,它会产生:
By default, it will produce :
Version A
Version A
当传递的类型是具有良好形状的模板模板时,如何强制使用版本B
(我可以添加新版本 f
,我可以添加 std :: enable_if
或其他C ++ 11类型traits语法,但如果可能,我想避免添加一个帮助类) ?
How to force the use of Version B
when the passed type is a template template with the good shape (I can add new versions of f
, I can add std::enable_if
or other C++11 type traits syntax, but if possible I would like to avoid adding an helper class) ?
推荐答案
std :: vector
c $ c> typename 参数,它需要2!不要忘记分配器。
std::vector
does not take a single typename
parameter, it takes 2! Don't forget the allocator.
因此,使用可变参数模板:
Thus, use variadic templates:
template<template<typename...> class T, typename T1>
void f(const T<T1>& x)
{
std::cout<<"Version B"<<std::endl;
}
现在可以按照您的需要工作。
Now it works as you want.
这篇关于当模板模板强制特定的重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文